def lockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService= CdiUtil.bean(CacheService)
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        status_attribute_value = userService.getCustomAttribute(find_user_by_uid, "gluuStatus")
        if status_attribute_value != None:
            user_status = status_attribute_value.getValue()
            if StringHelper.equals(user_status, "inactive"):
                print "Basic (lock account). Lock user. User '%s' locked already" % user_name
                return
        
        userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "inactive")
        updated_user = userService.updateUser(find_user_by_uid)

        object_to_store = json.dumps({'locked': True, 'created': LocalDateTime.now().toString()}, separators=(',',':'))

        cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store);
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Your account is locked. Please try again after " + StringHelper.toString(self.lockExpirationTime) + " secs")

        print "Basic (lock account). Lock user. User '%s' locked" % user_name
    def getUserProfile(self, jwt):
        # Check if there is user profile
        jwt_claims = jwt.getClaims()
        user_profile_json = jwt_claims.getClaimAsString("data")
        if StringHelper.isEmpty(user_profile_json):
            print "Passport. getUserProfile. User profile missing in JWT token"
            user_profile = None
        else:
            user_profile = self.getProfileFromJson(user_profile_json)

        return (user_profile, user_profile_json)
 def get_remote_ip_from_request(self, servletRequest):
     try:
         remote_ip = servletRequest.getHeader("X-FORWARDED-FOR")
         if StringHelper.isEmpty(remote_ip):
             remote_ip = servletRequest.getRemoteAddr()
         
         return remote_ip
     except:
         print "NetApi. Could not determine remote location: ", sys.exc_info()[1]
     
     return None
    def validateSessionId(self, identity):
        session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
        if StringHelper.isEmpty(session_id):
            print "OTP. Validate session id. Failed to determine session_id"
            return False

        otp_auth_method = identity.getWorkingParameter("otp_auth_method")
        if not otp_auth_method in ['enroll', 'authenticate']:
            print "OTP. Validate session id. Failed to authenticate user. otp_auth_method: '%s'" % otp_auth_method
            return False

        return True
    def isInboundJwt(self, value):
        if value == None:
            return False
        
        try:
            jwt = Jwt.parse(value)
            user_profile_json = jwt.getClaims().getClaimAsString("data")
            if StringHelper.isEmpty(user_profile_json):
                return False
        except:
            return False

        return True
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)

        if (step == 1):
            return True
        elif (step == 2):
            print "Fido2. Prepare for step 2"

            session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "Fido2. Prepare for step 2. Failed to determine session_id"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "Fido2. Prepare for step 2. Failed to determine user name"
                return False

            userName = user.getUserId()

            metaDataConfiguration = self.getMetaDataConfiguration()

            # Check if user have registered devices
            registrationPersistenceService = CdiUtil.bean(RegistrationPersistenceService)
            
            assertionResponse = None
            attestationResponse = None

            userFido2Devices = registrationPersistenceService.findAllRegisteredByUsername(userName)
            if (userFido2Devices.size() > 0):
                print "Fido2. Prepare for step 2. Call Fido2 endpoint in order to start assertion flow"

                try:
                    assertionService = Fido2ClientFactory.instance().createAssertionService(metaDataConfiguration)
                    assertionRequest = json.dumps({'username': userName}, separators=(',', ':'))
                    assertionResponse = assertionService.authenticate(assertionRequest).readEntity(java.lang.String)
                except ClientResponseFailure, ex:
                    print "Fido2. Prepare for step 2. Failed to start assertion flow. Exception:", sys.exc_info()[1]
                    return False
            else:
                print "Fido2. Prepare for step 2. Call Fido2 endpoint in order to start attestation flow"

                try:
                    attestationService = Fido2ClientFactory.instance().createAttestationService(metaDataConfiguration)
                    attestationRequest = json.dumps({'username': userName, 'displayName': userName}, separators=(',', ':'))
                    attestationResponse = attestationService.register(attestationRequest).readEntity(java.lang.String)
                except ClientResponseFailure, ex:
                    print "Fido2. Prepare for step 2. Failed to start attestation flow. Exception:", sys.exc_info()[1]
                    return False
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)

        if (step == 1):
            return True
        elif (step == 2):
            print "U2F. Prepare for step 2"

            session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "U2F. Prepare for step 2. Failed to determine session_id"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "U2F. Prepare for step 2. Failed to determine user name"
                return False

            u2f_application_id = configurationAttributes.get("u2f_application_id").getValue2()

            # Check if user have registered devices
            deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService)

            userInum = user.getAttribute("inum")

            registrationRequest = None
            authenticationRequest = None

            deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, u2f_application_id)
            if (deviceRegistrations.size() > 0):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to start authentication workflow"

                try:
                    authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration)
                    authenticationRequest = authenticationRequestService.startAuthentication(user.getUserId(), None, u2f_application_id, session_id)
                except ClientResponseFailure, ex:
                    if (ex.getResponse().getResponseStatus() != Response.Status.NOT_FOUND):
                        print "U2F. Prepare for step 2. Failed to start authentication workflow. Exception:", sys.exc_info()[1]
                        return False
            else:
                print "U2F. Prepare for step 2. Call FIDO U2F in order to start registration workflow"
                registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration)
                registrationRequest = registrationRequestService.startRegistration(user.getUserId(), u2f_application_id, session_id)

            identity.setWorkingParameter("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest))
            identity.setWorkingParameter("fido_u2f_registration_request", ServerUtil.asJson(registrationRequest))

            return True
    def authorize(self, context): # context is reference of org.gluu.oxauth.uma.authorization.UmaAuthorizationContext
        print "RPT Policy. Authorizing ..."

        client_id=context.getClient().getClientId()
        print "UmaRptPolicy. client_id = %s" % client_id

        if (StringHelper.isEmpty(client_id)):
            return False
     
        if (self.clientsSet.contains(client_id)):
            print "UmaRptPolicy. Authorizing client"
            return True
        else:
            print "UmaRptPolicy. Client isn't authorized"
            return False
    def setUserAttributeValue(self, user_name, attribute_name, attribute_value):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)

        find_user_by_uid = userService.getUser(user_name)
        if find_user_by_uid == None:
            return None
        
        userService.setCustomAttribute(find_user_by_uid, attribute_name, attribute_value)
        updated_user = userService.updateUser(find_user_by_uid)

        print "Basic (lock account). Set user attribute. User's '%s' attribute '%s' value is '%s'" % (user_name, attribute_name, attribute_value)

        return updated_user
    def getUserAttributeValue(self, user_name, attribute_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)

        find_user_by_uid = userService.getUser(user_name, attribute_name)
        if find_user_by_uid == None:
            return None

        custom_attribute_value = userService.getCustomAttribute(find_user_by_uid, attribute_name)
        if custom_attribute_value == None:
            return None
        
        attribute_value = custom_attribute_value.getValue()

        print "Basic (lock account). Get user attribute. User's '%s' attribute '%s' value is '%s'" % (user_name, attribute_name, attribute_value)

        return attribute_value
 def send_push_notification_to_user(self, sessionId,context):
     remote_ip = context.getHttpRequest().getParameter(self.remoteIpParamName)
     if remote_ip == None or (remote_ip != None and StringHelper.isEmpty(remote_ip)):
         remote_ip = self.networkApi.get_remote_ip_from_request(context.getHttpRequest())
     
     user = context.getUser()
     srbuilder = SuperGluuRequestBuilder()
     srbuilder.username = user.getUserId()
     srbuilder.app = self.applicationId
     srbuilder.issuer = self.issuerId
     srbuilder.state = sessionId.getId()
     srbuilder.requestLocation(self.networkApi.get_geolocation_data(remote_ip))
     srbuilder.req_ip = remote_ip 
     device_count = self.pushNotificationManager.sendPushNotification(user,self.applicationId,srbuilder.build())
     
     if device_count == 0:
         print "User %s has no device enrolled for Super-Gluu authentication" % user.getUserId()
         return False
     return True
    def unLockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService= CdiUtil.bean(CacheService)

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        object_to_store = json.dumps({'locked': False, 'created': LocalDateTime.now().toString()}, separators=(',',':'))
        cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store);

        userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "active")
        userService.setCustomAttribute(find_user_by_uid, self.invalidLoginCountAttribute, None)
        updated_user = userService.updateUser(find_user_by_uid)


        print "Basic (lock account). Lock user. User '%s' unlocked" % user_name
    def prepareClientRedirectUris(self, configurationAttributes):
        clientRedirectUrisSet = HashSet()
        if not configurationAttributes.containsKey("client_redirect_uris"):
            return clientRedirectUrisSet

        clientRedirectUrisList = configurationAttributes.get("client_redirect_uris").getValue2()
        if StringHelper.isEmpty(clientRedirectUrisList):
            print "Casa client registration. The property client_redirect_uris is empty"
            return clientRedirectUrisSet    

        clientRedirectUrisArray = StringHelper.split(clientRedirectUrisList, ",")
        if ArrayHelper.isEmpty(clientRedirectUrisArray):
            print "Casa client registration. No clients specified in client_redirect_uris property"
            return clientRedirectUrisSet
        
        # Convert to HashSet to quick search
        i = 0
        count = len(clientRedirectUrisArray)
        while i < count:
            uris = clientRedirectUrisArray[i]
            clientRedirectUrisSet.add(uris)
            i = i + 1

        return clientRedirectUrisSet
Example #14
0
    def prepareClientsSet(self, configurationAttributes):
        clientsSet = HashSet()
        if (not configurationAttributes.containsKey("allowed_clients")):
            return clientsSet

        allowedClientsList = configurationAttributes.get("allowed_clients").getValue2()
        if (StringHelper.isEmpty(allowedClientsList)):
            print "UMA authorization policy. Initialization. The property allowed_clients is empty"
            return clientsSet    

        allowedClientsListArray = StringHelper.split(allowedClientsList, ",")
        if (ArrayHelper.isEmpty(allowedClientsListArray)):
            print "UMA authorization policy. Initialization. There aren't clients specified in allowed_clients property"
            return clientsSet
        
        # Convert to HashSet to quick search
        i = 0
        count = len(allowedClientsListArray)
        while (i < count):
            client = allowedClientsListArray[i]
            clientsSet.add(client)
            i = i + 1

        return clientsSet
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        session_attributes = identity.getSessionId().getSessionAttributes()

        self.setRequestScopedParameters(identity)

        if (step == 1):
            print "UAF. Authenticate for step 1"

            user_name = credentials.getUsername()

            authenticated_user = self.processBasicAuthentication(credentials)
            if authenticated_user == None:
                return False

            uaf_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second device registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    uaf_auth_method = "enroll"
            
            if uaf_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 1. There is no UAF enrollment for user '%s'. Changing uaf_auth_method to '%s'" % (user_name, uaf_auth_method)

            print "UAF. Authenticate for step 1. uaf_auth_method: '%s'" % uaf_auth_method
            
            identity.setWorkingParameter("uaf_auth_method", uaf_auth_method)

            return True
        elif (step == 2):
            print "UAF. Authenticate for step 2"

            session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "UAF. Prepare for step 2. Failed to determine session_id"
                return False

            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "UAF. Authenticate for step 2. Failed to determine user name"
                return False
            user_name = user.getUserId()

            uaf_auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result")
            if uaf_auth_result != "success":
                print "UAF. Authenticate for step 2. auth_result is '%s'" % uaf_auth_result
                return False

            # Restore state from session
            uaf_auth_method = session_attributes.get("uaf_auth_method")

            if not uaf_auth_method in ['enroll', 'authenticate']:
                print "UAF. Authenticate for step 2. Failed to authenticate user. uaf_auth_method: '%s'" % uaf_auth_method
                return False

            # Request STATUS_OBB
            if True:
                #TODO: Remove this condition
                # It's workaround becuase it's not possible to call STATUS_OBB 2 times. First time on browser and second ime on server
                uaf_user_device_handle = ServerUtil.getFirstValue(requestParameters, "auth_handle")
            else:
                uaf_obb_auth_method = session_attributes.get("uaf_obb_auth_method")
                uaf_obb_server_uri = session_attributes.get("uaf_obb_server_uri")
                uaf_obb_start_response = session_attributes.get("uaf_obb_start_response")

                # Prepare STATUS_OBB
                uaf_obb_start_response_json = json.loads(uaf_obb_start_response)
                uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method,
                                                      "userName": user_name,
                                                      "needDetails": 1,
                                                      "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"],
                                                    }
    
                uaf_obb_status_request = json.dumps(uaf_obb_status_request_dictionary, separators=(',',':'))
                print "UAF. Authenticate for step 2. Prepared STATUS request: '%s' to send to '%s'" % (uaf_obb_status_request, uaf_obb_server_uri)

                uaf_status_obb_response = self.executePost(uaf_obb_server_uri, uaf_obb_status_request)
                if uaf_status_obb_response == None:
                    return False

                print "UAF. Authenticate for step 2. Get STATUS response: '%s'" % uaf_status_obb_response
                uaf_status_obb_response_json = json.loads(uaf_status_obb_response)
                
                if uaf_status_obb_response_json["statusCode"] != 4000:
                    print "UAF. Authenticate for step 2. UAF operation status is invalid. statusCode: '%s'" % uaf_status_obb_response_json["statusCode"]
                    return False

                uaf_user_device_handle = uaf_status_obb_response_json["additionalInfo"]["authenticatorsResult"]["handle"]

            if StringHelper.isEmpty(uaf_user_device_handle):
                print "UAF. Prepare for step 2. Failed to get UAF handle"
                return False

            uaf_user_external_uid = "uaf:%s" % uaf_user_device_handle
            print "UAF. Authenticate for step 2. UAF handle: '%s'" % uaf_user_external_uid

            if uaf_auth_method == "authenticate":
                # Validate if user used device with same keYHandle
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 2. There is no UAF enrollment for user '%s'." % user_name
                    return False
                
                for user_enrollment in user_enrollments:
                    if StringHelper.equalsIgnoreCase(user_enrollment, uaf_user_device_handle):
                        print "UAF. Authenticate for step 2. There is UAF enrollment for user '%s'. User authenticated successfully" % user_name
                        return True
            else:
                userService = CdiUtil.bean(UserService)

                # Double check just to make sure. We did checking in previous step
                # Check if there is user which has uaf_user_external_uid
                # Avoid mapping user cert to more than one IDP account
                find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", uaf_user_external_uid)
                if find_user_by_external_uid == None:
                    # Add uaf_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", uaf_user_external_uid)
                    if find_user_by_external_uid == None:
                        print "UAF. Authenticate for step 2. Failed to update current user"
                        return False
    
                    return True

            return False
        else:
            return False
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        session_attributes = identity.getSessionId().getSessionAttributes()

        self.setRequestScopedParameters(identity)

        if (step == 1):
            return True
        elif (step == 2):
            print "UAF. Prepare for step 2"

            session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie()
            if StringHelper.isEmpty(session_id):
                print "UAF. Prepare for step 2. Failed to determine session_id"
                return False

            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "UAF. Prepare for step 2. Failed to determine user name"
                return False

            uaf_auth_method = session_attributes.get("uaf_auth_method")
            if StringHelper.isEmpty(uaf_auth_method):
                print "UAF. Prepare for step 2. Failed to determine auth_method"
                return False

            print "UAF. Prepare for step 2. uaf_auth_method: '%s'" % uaf_auth_method

            uaf_obb_auth_method = "OOB_REG"
            uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/reg" 
            if StringHelper.equalsIgnoreCase(uaf_auth_method, "authenticate"):
                uaf_obb_auth_method = "OOB_AUTH"
                uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/auth" 

            # Prepare START_OBB
            uaf_obb_start_request_dictionary = { "operation": "START_%s" % uaf_obb_auth_method,
                                                 "userName": user.getUserId(),
                                                 "policyName": "default",
                                                 "oobMode":
                                                    { "qr": "true", "rawData": "false", "push": "false" } 
                                               }

            uaf_obb_start_request = json.dumps(uaf_obb_start_request_dictionary, separators=(',',':'))
            print "UAF. Prepare for step 2. Prepared START request: '%s' to send to '%s'" % (uaf_obb_start_request, uaf_obb_server_uri)

            # Request START_OBB
            uaf_obb_start_response = self.executePost(uaf_obb_server_uri, uaf_obb_start_request)
            if uaf_obb_start_response == None:
                return False

            print "UAF. Prepare for step 2. Get START response: '%s'" % uaf_obb_start_response
            uaf_obb_start_response_json = json.loads(uaf_obb_start_response)

            # Prepare STATUS_OBB
            #TODO: Remove needDetails parameter
            uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method,
                                                  "userName": user.getUserId(),
                                                  "needDetails": 1,
                                                  "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"],
                                                }

            uaf_obb_status_request = json.dumps(uaf_obb_status_request_dictionary, separators=(',',':'))
            print "UAF. Prepare for step 2. Prepared STATUS request: '%s' to send to '%s'" % (uaf_obb_status_request, uaf_obb_server_uri)

            identity.setWorkingParameter("uaf_obb_auth_method", uaf_obb_auth_method)
            identity.setWorkingParameter("uaf_obb_server_uri", uaf_obb_server_uri)
            identity.setWorkingParameter("uaf_obb_start_response", uaf_obb_start_response)
            identity.setWorkingParameter("qr_image", uaf_obb_start_response_json["modeResult"]["qrCode"]["qrImage"])
            identity.setWorkingParameter("uaf_obb_status_request", uaf_obb_status_request)

            return True
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Cert. Authenticate for step 1"
            login_button = ServerUtil.getFirstValue(requestParameters, "loginForm:loginButton")
            if StringHelper.isEmpty(login_button):
                print "Cert. Authenticate for step 1. Form were submitted incorrectly"
                return False
            if self.enabled_recaptcha:
                print "Cert. Authenticate for step 1. Validating recaptcha response"
                recaptcha_response = ServerUtil.getFirstValue(requestParameters, "g-recaptcha-response")

                recaptcha_result = self.validateRecaptcha(recaptcha_response)
                print "Cert. Authenticate for step 1. recaptcha_result: '%s'" % recaptcha_result
                
                return recaptcha_result

            return True
        elif step == 2:
            print "Cert. Authenticate for step 2"

            # Validate if user selected certificate
            cert_x509 = self.getSessionAttribute("cert_x509")
            if cert_x509 == None:
                print "Cert. Authenticate for step 2. User not selected any certs"
                identity.setWorkingParameter("cert_selected", False)
                    
                # Return True to inform user how to reset workflow
                return True
            else:
                identity.setWorkingParameter("cert_selected", True)
                x509Certificate = self.certFromString(cert_x509)

            subjectX500Principal = x509Certificate.getSubjectX500Principal()
            print "Cert. Authenticate for step 2. User selected certificate with DN '%s'" % subjectX500Principal
            
            # Validate certificates which user selected
            valid = self.validateCertificate(x509Certificate)
            if not valid:
                print "Cert. Authenticate for step 2. Certificate DN '%s' is not valid" % subjectX500Principal
                identity.setWorkingParameter("cert_valid", False)
                
                # Return True to inform user how to reset workflow
                return True

            identity.setWorkingParameter("cert_valid", True)
            
            # Calculate certificate fingerprint
            x509CertificateFingerprint = self.calculateCertificateFingerprint(x509Certificate)
            identity.setWorkingParameter("cert_x509_fingerprint", x509CertificateFingerprint)
            print "Cert. Authenticate for step 2. Fingerprint is '%s' of certificate with DN '%s'" % (x509CertificateFingerprint, subjectX500Principal)
            
            # Attempt to find user by certificate fingerprint
            cert_user_external_uid = "cert:%s" % x509CertificateFingerprint
            print "Cert. Authenticate for step 2. Attempting to find user by oxExternalUid attribute value %s" % cert_user_external_uid

            find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", cert_user_external_uid)
            if find_user_by_external_uid == None:
                print "Cert. Authenticate for step 2. Failed to find user"
                
                if self.map_user_cert:
                    print "Cert. Authenticate for step 2. Storing cert_user_external_uid for step 3"
                    identity.setWorkingParameter("cert_user_external_uid", cert_user_external_uid)
                    return True
                else:
                    print "Cert. Authenticate for step 2. Mapping cert to user account is not allowed"
                    identity.setWorkingParameter("cert_count_login_steps", 2)
                    return False

            foundUserName = find_user_by_external_uid.getUserId()
            print "Cert. Authenticate for step 2. foundUserName: "******"Cert. Authenticate for step 2. Setting count steps to 2"
            identity.setWorkingParameter("cert_count_login_steps", 2)

            return logged_in
        elif step == 3:
            print "Cert. Authenticate for step 3"

            cert_user_external_uid = self.getSessionAttribute("cert_user_external_uid")
            if cert_user_external_uid == None:
                print "Cert. Authenticate for step 3. cert_user_external_uid is empty"
                return False

            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                logged_in = authenticationService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            # Double check just to make sure. We did checking in previous step
            # Check if there is user which has cert_user_external_uid
            # Avoid mapping user cert to more than one IDP account
            find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", cert_user_external_uid)
            if find_user_by_external_uid == None:
                # Add cert_user_external_uid to user's external GUID list
                find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", cert_user_external_uid)
                if find_user_by_external_uid == None:
                    print "Cert. Authenticate for step 3. Failed to update current user"
                    return False

                return True
        
            return True
        else:
            return False
    def getTargetEndpointArn(self, platform, pushNotificationContext):
        
        deviceRegistrationService = pushNotificationContext.deviceRegistrationService
        pushSnsService = pushNotificationContext.pushSnsService
        user = pushNotificationContext.user
        u2fDevice  = pushNotificationContext.u2fDevice
        targetEndpointArn = None

        # Return endpoint ARN if it is created already
        notificationConf = u2fDevice.getDeviceNotificationConf()
        if StringHelper.isNotEmpty(notificationConf):
            notificationConfJson = json.loads(notificationConf)
            targetEndpointArn = notificationConfJson['sns_endpoint_arn']
            if StringHelper.isNotEmpty(targetEndpointArn):
                print "Super-Gluu-Push. Target endpoint ARN already created : ", targetEndpointArn
                return targetEndpointArn
        
        # Create endpoint ARN
        pushClient = None
        pushClientAuth = None
        platformApplicationArn = None
        if platform == PushPlatform.GCM:
            pushClient = self.pushAndroidService
            if self.pushSnsMode:
                platformApplicationArn = self.pushAndroidPlatformArn
            if self.pushGluuMode:
                pushClientAuth = self.pushAndroidServiceAuth
        elif platform == PushPlatform.APNS:
            pushClient = self.pushAppleService
            if self.pushSnsMode:
                platformApplicationArn = self.pushApplePlatformArn
            if self.pushGluuMode:
                pushClientAuth = self.pushAppleServiceAuth
        else:
            print "Super-Gluu-Push. Unsupported platform for ARN."
            return None
        
        deviceData = u2fDevice.getDeviceData()
        pushToken  = deviceData.getPushToken()

        print "Super-Gluu-Push. Attempting to create target endpoint ARN for user: %s" % user.getUserId()
        if self.pushSnsMode:
            targetEndpointArn = pushSnsService.createPlatformArn(pushClient,platformApplicationArn,pushToken,user)
        else:
            customUserData = pushSnsService.getCustomUserData(user)
            registerDeviceResponse = pushClient.registerDevice(pushClientAuth, pushToken, customUserData)
            if registerDeviceResponse != None and registerDeviceResponse.getStatusCode() == 200:
                targetEndpointArn = registerDeviceResponse.getEndpointArn()
        
        if StringHelper.isEmpty(targetEndpointArn):
            print "Super-Gluu-Push. Failed to get endpoint ARN for user: '******'" % user.getUserId()
            return None
        
        printmsg = "Super-Gluu-Push. Create target endpoint ARN '%s' for user '%s'"
        print printmsg % (targetEndpointArn, user.getUserId())
        
        # Store created endpoint ARN in device entry
        userInum = user.getAttribute("inum")
        u2fDeviceUpdate = deviceRegistrationService.findUserDeviceRegistration(userInum, u2fDevice.getId())
        u2fDeviceUpdate.setDeviceNotificationConf('{"sns_endpoint_arn": "%s"}' % targetEndpointArn)
        deviceRegistrationService.updateDeviceRegistration(userInum,u2fDeviceUpdate)

        return targetEndpointArn
    def processOtpAuthentication(self, requestParameters, user_name, identity, otp_auth_method):
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        userService = CdiUtil.bean(UserService)

        otpCode = ServerUtil.getFirstValue(requestParameters, "loginForm:otpCode")
        if StringHelper.isEmpty(otpCode):
            facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to authenticate. OTP code is empty")
            print "OTP. Process OTP authentication. otpCode is empty"

            return False
        
        if otp_auth_method == "enroll":
            # Get key from session
            otp_secret_key_encoded = identity.getWorkingParameter("otp_secret_key")
            if otp_secret_key_encoded == None:
                print "OTP. Process OTP authentication. OTP secret key is invalid"
                return False
            
            otp_secret_key = self.fromBase64Url(otp_secret_key_encoded)

            if self.otpType == "hotp":
                validation_result = self.validateHotpKey(otp_secret_key, 1, otpCode)
                
                if (validation_result != None) and validation_result["result"]:
                    print "OTP. Process HOTP authentication during enrollment. otpCode is valid"
                    # Store HOTP Secret Key and moving factor in user entry
                    otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] )

                    # Add otp_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid)
                    if find_user_by_external_uid != None:
                        return True

                    print "OTP. Process HOTP authentication during enrollment. Failed to update user entry"
            elif self.otpType == "totp":
                validation_result = self.validateTotpKey(otp_secret_key, otpCode)
                if (validation_result != None) and validation_result["result"]:
                    print "OTP. Process TOTP authentication during enrollment. otpCode is valid"
                    # Store TOTP Secret Key and moving factor in user entry
                    otp_user_external_uid = "totp:%s" % otp_secret_key_encoded

                    # Add otp_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid)
                    if find_user_by_external_uid != None:
                        return True

                    print "OTP. Process TOTP authentication during enrollment. Failed to update user entry"
        elif otp_auth_method == "authenticate":
            user_enrollments = self.findEnrollments(user_name)

            if len(user_enrollments) == 0:
                print "OTP. Process OTP authentication. There is no OTP enrollment for user '%s'" % user_name
                facesMessages.add(FacesMessage.SEVERITY_ERROR, "There is no valid OTP user enrollments")
                return False

            if self.otpType == "hotp":
                for user_enrollment in user_enrollments:
                    user_enrollment_data = user_enrollment.split(";")
                    otp_secret_key_encoded = user_enrollment_data[0]

                    # Get current moving factor from user entry
                    moving_factor = StringHelper.toInteger(user_enrollment_data[1])
                    otp_secret_key = self.fromBase64Url(otp_secret_key_encoded)

                    # Validate TOTP
                    validation_result = self.validateHotpKey(otp_secret_key, moving_factor, otpCode)
                    if (validation_result != None) and validation_result["result"]:
                        print "OTP. Process HOTP authentication during authentication. otpCode is valid"
                        otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, moving_factor )
                        new_otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] )
    
                        # Update moving factor in user entry
                        find_user_by_external_uid = userService.replaceUserAttribute(user_name, "oxExternalUid", otp_user_external_uid, new_otp_user_external_uid)
                        if find_user_by_external_uid != None:
                            return True
    
                        print "OTP. Process HOTP authentication during authentication. Failed to update user entry"
            elif self.otpType == "totp":
                for user_enrollment in user_enrollments:
                    otp_secret_key = self.fromBase64Url(user_enrollment)

                    # Validate TOTP
                    validation_result = self.validateTotpKey(otp_secret_key, otpCode)
                    if (validation_result != None) and validation_result["result"]:
                        print "OTP. Process TOTP authentication during authentication. otpCode is valid"
                        return True

        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to authenticate. OTP code is invalid")
        print "OTP. Process OTP authentication. OTP code is invalid"

        return False
    def authenticate(self, configurationAttributes, requestParameters, step):

        extensionResult = self.extensionAuthenticate(configurationAttributes, requestParameters, step)
        if extensionResult != None:
            return extensionResult

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            # Get JWT token
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")
            if jwt_param != None:
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                if not self.validSignature(jwt):
                    return False

                (user_profile, json) = self.getUserProfile(jwt)
                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile, json)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters, "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in

            elif provider in self.registeredProviders:
                #it's a recognized external IDP
                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"
                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters, "loginForm:email")
            json = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setEmailMessageError()
            elif json != None:
                # Completion of profile takes place
                user_profile = self.getProfileFromJson(json)
                user_profile["mail"] = mail

                return self.attemptAuthentication(identity, user_profile, json)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        session_attributes = identity.getSessionId().getSessionAttributes()

        self.setRequestScopedParameters(identity)

        if (step == 1):
            return True
        elif (step == 2):
            print "UAF. Prepare for step 2"

            session = CdiUtil.bean(SessionIdService).getSessionId()
            if session == None:
                print "UAF. Prepare for step 2. Failed to determine session_id"
                return False

            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "UAF. Prepare for step 2. Failed to determine user name"
                return False

            uaf_auth_method = session_attributes.get("uaf_auth_method")
            if StringHelper.isEmpty(uaf_auth_method):
                print "UAF. Prepare for step 2. Failed to determine auth_method"
                return False

            print "UAF. Prepare for step 2. uaf_auth_method: '%s'" % uaf_auth_method

            uaf_obb_auth_method = "OOB_REG"
            uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/reg" 
            if StringHelper.equalsIgnoreCase(uaf_auth_method, "authenticate"):
                uaf_obb_auth_method = "OOB_AUTH"
                uaf_obb_server_uri = self.uaf_server_uri + "/nnl/v2/auth" 

            # Prepare START_OBB
            uaf_obb_start_request_dictionary = { "operation": "START_%s" % uaf_obb_auth_method,
                                                 "userName": user.getUserId(),
                                                 "policyName": "default",
                                                 "oobMode":
                                                    { "qr": "true", "rawData": "false", "push": "false" } 
                                               }

            uaf_obb_start_request = json.dumps(uaf_obb_start_request_dictionary, separators=(',',':'))
            print "UAF. Prepare for step 2. Prepared START request: '%s' to send to '%s'" % (uaf_obb_start_request, uaf_obb_server_uri)

            # Request START_OBB
            uaf_obb_start_response = self.executePost(uaf_obb_server_uri, uaf_obb_start_request)
            if uaf_obb_start_response == None:
                return False

            print "UAF. Prepare for step 2. Get START response: '%s'" % uaf_obb_start_response
            uaf_obb_start_response_json = json.loads(uaf_obb_start_response)

            # Prepare STATUS_OBB
            #TODO: Remove needDetails parameter
            uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method,
                                                  "userName": user.getUserId(),
                                                  "needDetails": 1,
                                                  "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"],
                                                }

            uaf_obb_status_request = json.dumps(uaf_obb_status_request_dictionary, separators=(',',':'))
            print "UAF. Prepare for step 2. Prepared STATUS request: '%s' to send to '%s'" % (uaf_obb_status_request, uaf_obb_server_uri)

            identity.setWorkingParameter("uaf_obb_auth_method", uaf_obb_auth_method)
            identity.setWorkingParameter("uaf_obb_server_uri", uaf_obb_server_uri)
            identity.setWorkingParameter("uaf_obb_start_response", uaf_obb_start_response)
            identity.setWorkingParameter("qr_image", uaf_obb_start_response_json["modeResult"]["qrCode"]["qrImage"])
            identity.setWorkingParameter("uaf_obb_status_request", uaf_obb_status_request)

            return True
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        session_attributes = identity.getSessionId().getSessionAttributes()

        self.setRequestScopedParameters(identity)

        if (step == 1):
            print "UAF. Authenticate for step 1"

            user_name = credentials.getUsername()

            authenticated_user = self.processBasicAuthentication(credentials)
            if authenticated_user == None:
                return False

            uaf_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second device registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    uaf_auth_method = "enroll"
            
            if uaf_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 1. There is no UAF enrollment for user '%s'. Changing uaf_auth_method to '%s'" % (user_name, uaf_auth_method)

            print "UAF. Authenticate for step 1. uaf_auth_method: '%s'" % uaf_auth_method
            
            identity.setWorkingParameter("uaf_auth_method", uaf_auth_method)

            return True
        elif (step == 2):
            print "UAF. Authenticate for step 2"

            session = CdiUtil.bean(SessionIdService).getSessionId()
            if session == None:
                print "UAF. Prepare for step 2. Failed to determine session_id"
                return False

            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "UAF. Authenticate for step 2. Failed to determine user name"
                return False
            user_name = user.getUserId()

            uaf_auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result")
            if uaf_auth_result != "success":
                print "UAF. Authenticate for step 2. auth_result is '%s'" % uaf_auth_result
                return False

            # Restore state from session
            uaf_auth_method = session_attributes.get("uaf_auth_method")

            if not uaf_auth_method in ['enroll', 'authenticate']:
                print "UAF. Authenticate for step 2. Failed to authenticate user. uaf_auth_method: '%s'" % uaf_auth_method
                return False

            # Request STATUS_OBB
            if True:
                #TODO: Remove this condition
                # It's workaround becuase it's not possible to call STATUS_OBB 2 times. First time on browser and second ime on server
                uaf_user_device_handle = ServerUtil.getFirstValue(requestParameters, "auth_handle")
            else:
                uaf_obb_auth_method = session_attributes.get("uaf_obb_auth_method")
                uaf_obb_server_uri = session_attributes.get("uaf_obb_server_uri")
                uaf_obb_start_response = session_attributes.get("uaf_obb_start_response")

                # Prepare STATUS_OBB
                uaf_obb_start_response_json = json.loads(uaf_obb_start_response)
                uaf_obb_status_request_dictionary = { "operation": "STATUS_%s" % uaf_obb_auth_method,
                                                      "userName": user_name,
                                                      "needDetails": 1,
                                                      "oobStatusHandle": uaf_obb_start_response_json["oobStatusHandle"],
                                                    }
    
                uaf_obb_status_request = json.dumps(uaf_obb_status_request_dictionary, separators=(',',':'))
                print "UAF. Authenticate for step 2. Prepared STATUS request: '%s' to send to '%s'" % (uaf_obb_status_request, uaf_obb_server_uri)

                uaf_status_obb_response = self.executePost(uaf_obb_server_uri, uaf_obb_status_request)
                if uaf_status_obb_response == None:
                    return False

                print "UAF. Authenticate for step 2. Get STATUS response: '%s'" % uaf_status_obb_response
                uaf_status_obb_response_json = json.loads(uaf_status_obb_response)
                
                if uaf_status_obb_response_json["statusCode"] != 4000:
                    print "UAF. Authenticate for step 2. UAF operation status is invalid. statusCode: '%s'" % uaf_status_obb_response_json["statusCode"]
                    return False

                uaf_user_device_handle = uaf_status_obb_response_json["additionalInfo"]["authenticatorsResult"]["handle"]

            if StringHelper.isEmpty(uaf_user_device_handle):
                print "UAF. Prepare for step 2. Failed to get UAF handle"
                return False

            uaf_user_external_uid = "uaf:%s" % uaf_user_device_handle
            print "UAF. Authenticate for step 2. UAF handle: '%s'" % uaf_user_external_uid

            if uaf_auth_method == "authenticate":
                # Validate if user used device with same keYHandle
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 2. There is no UAF enrollment for user '%s'." % user_name
                    return False
                
                for user_enrollment in user_enrollments:
                    if StringHelper.equalsIgnoreCase(user_enrollment, uaf_user_device_handle):
                        print "UAF. Authenticate for step 2. There is UAF enrollment for user '%s'. User authenticated successfully" % user_name
                        return True
            else:
                userService = CdiUtil.bean(UserService)

                # Double check just to make sure. We did checking in previous step
                # Check if there is user which has uaf_user_external_uid
                # Avoid mapping user cert to more than one IDP account
                find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", uaf_user_external_uid)
                if find_user_by_external_uid == None:
                    # Add uaf_user_external_uid to user's external GUID list
                    find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", uaf_user_external_uid)
                    if find_user_by_external_uid == None:
                        print "UAF. Authenticate for step 2. Failed to update current user"
                        return False
    
                    return True

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        self.setRequestScopedParameters(identity)

        if step == 1:
            print "OTP. Authenticate for step 1"
            authenticated_user = self.processBasicAuthentication(credentials)
            if authenticated_user == None:
                return False

            otp_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second OTP registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    otp_auth_method = "enroll"
            
            if otp_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(authenticated_user.getUserId())
                if len(user_enrollments) == 0:
                    otp_auth_method = "enroll"
                    print "OTP. Authenticate for step 1. There is no OTP enrollment for user '%s'. Changing otp_auth_method to '%s'" % (authenticated_user.getUserId(), otp_auth_method)
                    
            if otp_auth_method == "enroll":
                print "OTP. Authenticate for step 1. Setting count steps: '%s'" % 3
                identity.setWorkingParameter("otp_count_login_steps", 3)

            print "OTP. Authenticate for step 1. otp_auth_method: '%s'" % otp_auth_method
            identity.setWorkingParameter("otp_auth_method", otp_auth_method)

            return True
        elif step == 2:
            print "OTP. Authenticate for step 2"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP. Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method == 'enroll':
                auth_result = ServerUtil.getFirstValue(requestParameters, "auth_result")
                if not StringHelper.isEmpty(auth_result):
                    print "OTP. Authenticate for step 2. User not enrolled OTP"
                    return False

                print "OTP. Authenticate for step 2. Skipping this step during enrollment"
                return True

            otp_auth_result = self.processOtpAuthentication(requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP. Authenticate for step 2. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        elif step == 3:
            print "OTP. Authenticate for step 3"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP. Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method != 'enroll':
                return False

            otp_auth_result = self.processOtpAuthentication(requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP. Authenticate for step 3. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        userService = CdiUtil.bean(UserService)
        requestParameterService = CdiUtil.bean(RequestParameterService)
        authenticationService = CdiUtil.bean(AuthenticationService)
        httpService = CdiUtil.bean(HttpService)

        if step == 1:
            print "CAS2. Authenticate for step 1"
            ticket_array = requestParameters.get("ticket")
            if ArrayHelper.isEmpty(ticket_array):
                print "CAS2. Authenticate for step 1. ticket is empty"
                return False

            ticket = ticket_array[0]
            print "CAS2. Authenticate for step 1. ticket: " + ticket

            if StringHelper.isEmptyString(ticket):
                print "CAS2. Authenticate for step 1. ticket is invalid"
                return False

            # Validate ticket
            facesContext = CdiUtil.bean(FacesContext)
            request = facesContext.getExternalContext().getRequest()

            parametersMap = HashMap()
            parametersMap.put("service", httpService.constructServerUrl(request) + "/postlogin.htm")
            if self.cas_renew_opt:
                parametersMap.put("renew", "true")
            parametersMap.put("ticket", ticket)
            cas_service_request_uri = requestParameterService.parametersAsString(parametersMap)
            cas_service_request_uri = self.cas_host + "/serviceValidate?" + cas_service_request_uri
            if self.cas_extra_opts != None:
                cas_service_request_uri = cas_service_request_uri + "&" + self.cas_extra_opts

            print "CAS2. Authenticate for step 1. cas_service_request_uri: " + cas_service_request_uri

            http_client = httpService.getHttpsClient()
            http_service_response = httpService.executeGet(http_client, cas_service_request_uri)
            try:
                validation_content = httpService.convertEntityToString(httpService.getResponseContent(http_service_response.getHttpResponse()))
            finally:
                http_service_response.closeConnection()

            print "CAS2. Authenticate for step 1. validation_content: " + validation_content
            if StringHelper.isEmpty(validation_content):
                print "CAS2. Authenticate for step 1. Ticket validation response is invalid"
                return False

            cas2_auth_failure = self.parse_tag(validation_content, "cas:authenticationFailure")
            print "CAS2. Authenticate for step 1. cas2_auth_failure: ", cas2_auth_failure

            cas2_user_uid = self.parse_tag(validation_content, "cas:user")
            print "CAS2. Authenticate for step 1. cas2_user_uid: ", cas2_user_uid
            
            if (cas2_auth_failure != None) or (cas2_user_uid == None):
                print "CAS2. Authenticate for step 1. Ticket is invalid"
                return False

            if self.cas_map_user:
                print "CAS2. Authenticate for step 1. Attempting to find user by oxExternalUid: cas2:" + cas2_user_uid

                # Check if the is user with specified cas2_user_uid
                find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "cas2:" + cas2_user_uid)

                if find_user_by_uid == None:
                    print "CAS2. Authenticate for step 1. Failed to find user"
                    print "CAS2. Authenticate for step 1. Setting count steps to 2"
                    identity.setWorkingParameter("cas2_count_login_steps", 2)
                    identity.setWorkingParameter("cas2_user_uid", cas2_user_uid)
                    return True

                found_user_name = find_user_by_uid.getUserId()
                print "CAS2. Authenticate for step 1. found_user_name: " + found_user_name
                
                authenticationService.authenticate(found_user_name)
            
                print "CAS2. Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("cas2_count_login_steps", 1)

                return True
            else:
                print "CAS2. Authenticate for step 1. Attempting to find user by uid:" + cas2_user_uid

                # Check if there is user with specified cas2_user_uid
                find_user_by_uid = userService.getUser(cas2_user_uid)
                if find_user_by_uid == None:
                    print "CAS2. Authenticate for step 1. Failed to find user"
                    return False

                found_user_name = find_user_by_uid.getUserId()
                print "CAS2. Authenticate for step 1. found_user_name: " + found_user_name

                authenticationService.authenticate(found_user_name)

                print "CAS2. Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("cas2_count_login_steps", 1)

                return True
        elif step == 2:
            print "CAS2. Authenticate for step 2"

            if identity.isSetWorkingParameter("cas2_user_uid"):
                print "CAS2. Authenticate for step 2. cas2_user_uid is empty"
                return False

            cas2_user_uid = identity.getWorkingParameter("cas2_user_uid")
            passed_step1 = StringHelper.isNotEmptyString(cas2_user_uid)
            if not passed_step1:
                return False

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            logged_in = False
            if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                logged_in = authenticationService.authenticate(user_name, user_password)

            if not logged_in:
                return False

            # Check if there is user which has cas2_user_uid
            # Avoid mapping CAS2 account to more than one IDP account
            find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "cas2:" + cas2_user_uid)

            if find_user_by_uid == None:
                # Add cas2_user_uid to user one id UIDs
                find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "cas2:" + cas2_user_uid)
                if find_user_by_uid == None:
                    print "CAS2. Authenticate for step 2. Failed to update current user"
                    return False

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "CAS2. Authenticate for step 2. found_user_name: " + found_user_name
    
                if StringHelper.equals(user_name, found_user_name):
                    return True
        
            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):

        extensionResult = self.extensionAuthenticate(configurationAttributes,
                                                     requestParameters, step)
        if extensionResult != None:
            return extensionResult

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            jwt_param = None
            if self.isInboundFlow(identity):
                print "Passport. authenticate for step 1. Detected idp-initiated inbound Saml flow"
                jwt_param = identity.getSessionId().getSessionAttributes().get(
                    AuthorizeRequestParam.STATE)

            if jwt_param == None:
                jwt_param = ServerUtil.getFirstValue(requestParameters, "user")

            if jwt_param != None:
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                if not self.validSignature(jwt):
                    return False

                if self.jwtHasExpired(jwt):
                    return False

                (user_profile, jsonp) = self.getUserProfile(jwt)
                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile,
                                                  jsonp)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters,
                                                "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(
                        user_name) and StringHelper.isNotEmptyString(
                            user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in

            elif provider in self.registeredProviders:
                #it's a recognized external IDP
                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"
                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters,
                                            "loginForm:email")
            jsonp = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setMessageError(FacesMessage.SEVERITY_ERROR,
                                     "Email was missing in user profile")
            elif jsonp != None:
                # Completion of profile takes place
                user_profile = json.loads(jsonp)
                user_profile["mail"] = mail

                return self.attemptAuthentication(identity, user_profile,
                                                  jsonp)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False