def init(self, configurationAttributes):
        print "PhoneFactor. Initialization"
        pf_cert_path = configurationAttributes.get("pf_cert_path").getValue2()
        pf_creds_file = configurationAttributes.get("pf_creds_file").getValue2()

        # Load credentials from file
        f = open(pf_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        certPassword = creds["CERT_PASSWORD"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            certPassword = stringEncrypter.decrypt(certPassword)
        except:
            return False

        self.pf.initialize(pf_cert_path, certPassword)
        print "PhoneFactor. Initialized successfully"

        return True
Example #2
0
    def init(self, configurationAttributes):
        print "InWebo. Initialization"

        iw_cert_store_type = configurationAttributes.get(
            "iw_cert_store_type").getValue2()
        iw_cert_path = configurationAttributes.get("iw_cert_path").getValue2()
        iw_creds_file = configurationAttributes.get(
            "iw_creds_file").getValue2()

        # Load credentials from file
        f = open(iw_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        iw_cert_password = creds["CERT_PASSWORD"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            iw_cert_password = stringEncrypter.decrypt(iw_cert_password)
        except:
            return False

        httpService = HttpService.instance()
        self.client = httpService.getHttpsClient(None, None, None,
                                                 iw_cert_store_type,
                                                 iw_cert_path,
                                                 iw_cert_password)
        print "InWebo. Initialized successfully"

        return True
Example #3
0
    def init(self, configurationAttributes):
        print "Shibboleth initialization"

        idp_cert_store_type = configurationAttributes.get("idp_cert_store_type").getValue2()
        idp_cert_path = configurationAttributes.get("idp_cert_path").getValue2()
        idp_creds_file = configurationAttributes.get("idp_creds_file").getValue2()

        # Load credentials from file
        f = open(idp_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        idp_cert_password = creds["CERT_PASSWORD"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            idp_cert_password = stringEncrypter.decrypt(idp_cert_password)
        except:
            return False

        self.sb.initialize(idp_cert_store_type, idp_cert_path, idp_cert_password)
        print "Shibboleth initialized successfully"

        return True   
Example #4
0
    def init(self, configurationAttributes):
        print "Toopher. Initialization"
        toopher_creds_file = configurationAttributes.get(
            "toopher_creds_file").getValue2()

        # Load credentials from file
        f = open(toopher_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        consumer_key = creds["CONSUMER_KEY"]
        consumer_secret = creds["CONSUMER_SECRET"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            consumer_secret = stringEncrypter.decrypt(consumer_secret)
        except:
            return False

        self.tapi = ToopherAPI(consumer_key, consumer_secret)
        print "Toopher. Initialized successfully"

        return True
    def init(self, configurationAttributes):
        print "InWebo. Initialization"

        iw_cert_store_type = configurationAttributes.get("iw_cert_store_type").getValue2()
        iw_cert_path = configurationAttributes.get("iw_cert_path").getValue2()
        iw_creds_file = configurationAttributes.get("iw_creds_file").getValue2()

        # Load credentials from file
        f = open(iw_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        iw_cert_password = creds["CERT_PASSWORD"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            iw_cert_password = stringEncrypter.decrypt(iw_cert_password)
        except:
            return False

        httpService = HttpService.instance()
        self.client = httpService.getHttpsClient(None, None, None, iw_cert_store_type, iw_cert_path, iw_cert_password)
        print "InWebo. Initialized successfully"

        return True   
    def init(self, configurationAttributes):
        print "Toopher initialization"
        toopher_creds_file = configurationAttributes.get("toopher_creds_file").getValue2()

        # Load credentials from file
        f = open(toopher_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        consumer_key = creds["CONSUMER_KEY"]
        consumer_secret = creds["CONSUMER_SECRET"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            consumer_secret = stringEncrypter.decrypt(consumer_secret)
        except:
            return False

        self.tapi = ToopherAPI(consumer_key, consumer_secret)
        print "Toopher initialized successfully"

        return True
Example #7
0
    def init(self, configurationAttributes):
        print "PhoneFactor. Initialization"
        pf_cert_path = configurationAttributes.get("pf_cert_path").getValue2()
        pf_creds_file = configurationAttributes.get(
            "pf_creds_file").getValue2()

        # Load credentials from file
        f = open(pf_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        certPassword = creds["CERT_PASSWORD"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            certPassword = stringEncrypter.decrypt(certPassword)
        except:
            return False

        self.pf.initialize(pf_cert_path, certPassword)
        print "PhoneFactor. Initialized successfully"

        return True
    def initRecaptcha(self, configurationAttributes):
        print "Cert. Initialize recaptcha"
        if not configurationAttributes.containsKey("credentials_file"):
            return False

        cert_creds_file = configurationAttributes.get(
            "credentials_file").getValue2()

        # Load credentials from file
        f = open(cert_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            print "Cert. Initialize recaptcha. Failed to load credentials from file: %s" % cert_creds_file
            return False
        finally:
            f.close()

        try:
            recaptcha_creds = creds["recaptcha"]
        except:
            print "Cert. Initialize recaptcha. Invalid credentials file '%s' format:" % cert_creds_file
            return False

        self.recaptcha_creds = None
        if recaptcha_creds["enabled"]:
            print "Cert. Initialize recaptcha. Recaptcha is enabled"

            stringEncrypter = StringEncrypter.defaultInstance()

            site_key = recaptcha_creds["site_key"]
            secret_key = recaptcha_creds["secret_key"]

            try:
                site_key = stringEncrypter.decrypt(site_key)
            except:
                # Ignore exception. Value is not encrypted
                print "Cert. Initialize recaptcha. Assuming that 'site_key' in not encrypted"

            try:
                secret_key = stringEncrypter.decrypt(secret_key)
            except:
                # Ignore exception. Value is not encrypted
                print "Cert. Initialize recaptcha. Assuming that 'secret_key' in not encrypted"

            self.recaptcha_creds = {
                'site_key': site_key,
                "secret_key": secret_key
            }
            print "Cert. Initialize recaptcha. Recaptcha is configured correctly"

            return True
        else:
            print "Cert. Initialize recaptcha. Recaptcha is disabled"

        return False
    def initPushNotificationService(self, configurationAttributes):
        print "Super-Gluu. Initialize notification services"
        if not configurationAttributes.containsKey("credentials_file"):
            return False

        super_gluu_creds_file = configurationAttributes.get(
            "credentials_file").getValue2()

        # Load credentials from file
        f = open(super_gluu_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            print "Super-Gluu. Initialize notification services. Failed to load credentials from file:", super_gluu_creds_file
            return False
        finally:
            f.close()

        try:
            android_creds = creds["android"]["gcm"]
            ios_creads = creds["ios"]["apns"]
        except:
            print "Super-Gluu. Initialize notification services. Invalid credentials file '%s' format:" % super_gluu_creds_file
            return False

        self.pushAndroidService = None
        self.pushAppleService = None
        if android_creds["enabled"]:
            self.pushAndroidService = Sender(android_creds["api_key"])
            print "Super-Gluu. Initialize notification services. Created Android notification service"

        if ios_creads["enabled"]:
            p12_file_path = ios_creads["p12_file_path"]
            p12_passowrd = ios_creads["p12_password"]

            try:
                stringEncrypter = StringEncrypter.defaultInstance()
                p12_passowrd = stringEncrypter.decrypt(p12_passowrd)
            except:
                # Ignore exception. Password is not encrypted
                print "Super-Gluu. Initialize notification services. Assuming that 'p12_passowrd' password in not encrypted"

            apnsServiceBuilder = APNS.newService().withCert(
                p12_file_path, p12_passowrd)
            if ios_creads["production"]:
                self.pushAppleService = apnsServiceBuilder.withProductionDestination(
                ).build()
            else:
                self.pushAppleService = apnsServiceBuilder.withSandboxDestination(
                ).build()

            print "Super-Gluu. Initialize notification services. Created iOS notification service"

        enabled = self.pushAndroidService != None or self.pushAppleService != None

        return enabled
    def initRecaptcha(self, configurationAttributes):
        print "Cert. Initialize recaptcha"
        if not configurationAttributes.containsKey("credentials_file"):
            return False

        cert_creds_file = configurationAttributes.get("credentials_file").getValue2()

        # Load credentials from file
        f = open(cert_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            print "Cert. Initialize recaptcha. Failed to load credentials from file: %s" % cert_creds_file
            return False
        finally:
            f.close()
        
        try:
            recaptcha_creds = creds["recaptcha"]
        except:
            print "Cert. Initialize recaptcha. Invalid credentials file '%s' format:" % cert_creds_file
            return False
        
        self.recaptcha_creds = None
        if recaptcha_creds["enabled"]:
            print "Cert. Initialize recaptcha. Recaptcha is enabled"

            stringEncrypter = StringEncrypter.defaultInstance()

            site_key = recaptcha_creds["site_key"]
            secret_key = recaptcha_creds["secret_key"]

            try:
                site_key = stringEncrypter.decrypt(site_key)
            except:
                # Ignore exception. Value is not encrypted
                print "Cert. Initialize recaptcha. Assuming that 'site_key' in not encrypted"

            try:
                secret_key = stringEncrypter.decrypt(secret_key)
            except:
                # Ignore exception. Value is not encrypted
                print "Cert. Initialize recaptcha. Assuming that 'secret_key' in not encrypted"

            
            self.recaptcha_creds = { 'site_key' : site_key, "secret_key" : secret_key }
            print "Cert. Initialize recaptcha. Recaptcha is configured correctly"

            return True
        else:
            print "Cert. Initialize recaptcha. Recaptcha is disabled"

        return False
    def initPushNotificationService(self, configurationAttributes):
        print "Super-Gluu. Initialize notification services"
        if not configurationAttributes.containsKey("credentials_file"):
            return False

        super_gluu_creds_file = configurationAttributes.get("credentials_file").getValue2()

        # Load credentials from file
        f = open(super_gluu_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            print "Super-Gluu. Initialize notification services. Failed to load credentials from file:", super_gluu_creds_file
            return False
        finally:
            f.close()
        
        try:
            android_creds = creds["android"]["gcm"]
            ios_creads = creds["ios"]["apns"]
        except:
            print "Super-Gluu. Initialize notification services. Invalid credentials file '%s' format:" % super_gluu_creds_file
            return False
        
        self.pushAndroidService = None
        self.pushAppleService = None
        if android_creds["enabled"]:
            self.pushAndroidService = Sender(android_creds["api_key"]) 
            print "Super-Gluu. Initialize notification services. Created Android notification service"
            
        if ios_creads["enabled"]:
            p12_file_path = ios_creads["p12_file_path"]
            p12_passowrd = ios_creads["p12_password"]

            try:
                stringEncrypter = StringEncrypter.defaultInstance()
                p12_passowrd = stringEncrypter.decrypt(p12_passowrd)
            except:
                # Ignore exception. Password is not encrypted
                print "Super-Gluu. Initialize notification services. Assuming that 'p12_passowrd' password in not encrypted"

            apnsServiceBuilder =  APNS.newService().withCert(p12_file_path, p12_passowrd)
            if ios_creads["production"]:
                self.pushAppleService = apnsServiceBuilder.withProductionDestination().build()
            else:
                self.pushAppleService = apnsServiceBuilder.withSandboxDestination().build()

            print "Super-Gluu. Initialize notification services. Created iOS notification service"

        enabled = self.pushAndroidService != None or self.pushAppleService != None

        return enabled
    def initPushNotificationService(self, configurationAttributes):
        print "oxPush2. Initialize notification services"
        if not configurationAttributes.containsKey("credentials_file"):
            return False

        oxpush2_creds_file = configurationAttributes.get("credentials_file").getValue2()

        # Load credentials from file
        f = open(oxpush2_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            print "oxPush2. Initialize notification services. Failed to load credentials from file:", oxpush2_creds_file
            return False
        finally:
            f.close()
        
        try:
            android_creds = creds["android"]["gcm"]
            ios_creads = creds["ios"]["apns"]
        except:
            print "oxPush2. Initialize notification services. Invalid credentials file '%s' format:" % oxpush2_creds_file
            return False
        
        self.pushAndroidService = None
        self.pushAppleService = None
        if android_creds["enabled"]:
            self.pushAndroidService = SyncAndroidPushService(android_creds["api_key"])
            print "oxPush2. Initialize notification services. Created Android notification service"
            
        if ios_creads["enabled"]:
            p12_file_path = ios_creads["p12_file_path"]
            p12_passowrd = ios_creads["p12_password"]

            try:
                stringEncrypter = StringEncrypter.defaultInstance()
                p12_passowrd = stringEncrypter.decrypt(p12_passowrd)
            except:
                # Ignore exception. Password is not encrypted
                print "oxPush2. Initialize notification services. Assuming that 'p12_passowrd' password in not encrypted"

            self.pushAppleService = SyncApplePushService(p12_file_path, p12_passowrd, ios_creads["production"])
            print "oxPush2. Initialize notification services. Created iOS notification service"

        enabled = self.pushAndroidService != None or self.pushAppleService != None

        return enabled
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        stringEncrypter = StringEncrypter.defaultInstance()

        context = Contexts.getEventContext()

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

        if (step == 1):
            print "oxPush prepare for step 1"
            oxpush_android_download_url = configurationAttributes.get("oxpush_android_download_url").getValue2()
            context.set("oxpush_android_download_url", oxpush_android_download_url)
        elif (step == 2):
            print "oxPush prepare for step 2"

            passed_step1 = self.isPassedDefaultAuthentication
            if (not passed_step1):
                return False

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()

            oxpush_user_uid_array = requestParameters.get("oxpush_user_uid")
            if (ArrayHelper.isEmpty(oxpush_user_uid_array) or StringHelper.isEmptyString(oxpush_user_uid_array[0])):
                print "oxPush prepare for step 2. oxpush_user_uid is empty"

                # Initialize pairing process
                pairing_process = None
                try:
                    pairing_process = self.oxPushClient.pair(oxpush_application_name, user_name);
                except java.lang.Exception, err:
                    print "oxPush prepare for step 2. Failed to initialize pairing process: ", err
                    return False

                if (not pairing_process.result):
                    print "oxPush prepare for step 2. Failed to initialize pairing process"
                    return False

                pairing_id = pairing_process.pairingId
                print "oxPush prepare for step 2. Pairing Id: ", pairing_id
    
                context.set("oxpush_pairing_uid", stringEncrypter.encrypt(pairing_id))
                context.set("oxpush_pairing_code", pairing_process.pairingCode)
                context.set("oxpush_pairing_qr_image", pairing_process.pairingQrImage)
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()

        stringEncrypter = StringEncrypter.defaultInstance()

        toopher_user_timeout = int(configurationAttributes.get("toopher_user_timeout").getValue2())

        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        if (step == 1):
            print "Toopher authenticate for step 1"

            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                userService = UserService.instance()
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            # Find user by uid
            userService = UserService.instance()
            find_user_by_uid = userService.getUser(user_name)
            if (find_user_by_uid == None):
                print "Toopher authenticate for step 1. Failed to find user"
                return False

            # Check if the user paired account to phone
            user_external_uid_attr = userService.getCustomAttribute(find_user_by_uid, "oxExternalUid")
            if ((user_external_uid_attr == None) or (user_external_uid_attr.getValues() == None)):
                print "Toopher authenticate for step 1. There is no external UIDs for user: "******"Toopher authenticate for step 1. There is no Topher UID for user: "******"toopher_user_uid", stringEncrypter.encrypt(topher_user_uid))

            return True
        elif (step == 2):
            print "Toopher authenticate for step 2"

            passed_step1 = self.isPassedDefaultAuthentication
            if (not passed_step1):
                return False

            toopher_user_uid_array = requestParameters.get("toopher_user_uid")
            
            if (ArrayHelper.isEmpty(toopher_user_uid_array) or StringHelper.isEmptyString(toopher_user_uid_array[0])):
                print "Toopher authenticate for step 2. toopher_user_uid is empty"

                # Pair with phone
                pairing_phrase_array = requestParameters.get("pairing_phrase")
                if ArrayHelper.isEmpty(pairing_phrase_array):
                    print "Toopher authenticate for step 2. pairing_phrase is empty"
                    return False
                
                pairing_phrase = pairing_phrase_array[0]
                try:
                    pairing_status = self.tapi.pair(pairing_phrase, user_name);
                    toopher_user_uid = pairing_status.id;
                except RequestError, err:
                    print "Toopher authenticate for step 2. Failed pair with phone: ", err
                    return False
                
                pairing_result = self.checkPairingStatus(toopher_user_uid, toopher_user_timeout) 

                if (not pairing_result):
                    print "Toopher authenticate for step 2. The pairing has not been authorized by the phone yet"
                    return False
                    
                print "Toopher authenticate for step 2. Storing toopher_user_uid in user entry", toopher_user_uid

                # Store toopher_user_uid in user entry
                find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "toopher:" + toopher_user_uid)
                if (find_user_by_uid == None):
                    print "Toopher authenticate for step 2. Failed to update current user"
                    return False

                context.set("toopher_user_uid", stringEncrypter.encrypt(toopher_user_uid))
            else:
                toopher_user_uid = stringEncrypter.decrypt(toopher_user_uid_array[0])

                # Check pairing stastus
                print "Toopher authenticate for step 2. toopher_user_uid: ", toopher_user_uid
                pairing_result = self.checkPairingStatus(toopher_user_uid, 0) 
                if (not pairing_result):
                    print "Toopher authenticate for step 2. The pairing has not been authorized by the phone yet"
                    return False

            return True
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()
        httpService = HttpService.instance();

        stringEncrypter = StringEncrypter.defaultInstance()

        server_flag = configurationAttributes.get("oneid_server_flag").getValue2()
        callback_attrs = configurationAttributes.get("oneid_callback_attrs").getValue2()
        creds_file = configurationAttributes.get("oneid_creds_file").getValue2()

        # Create OneID
        authn = OneID(server_flag)

        # Set path to credentials file
        authn.creds_file = creds_file;

        if (step == 1):
            print "OneID authenticate for step 1"

            # Find OneID request
            json_data_array = requestParameters.get("json_data")
            if ArrayHelper.isEmpty(json_data_array):
                print "OneID authenticate for step 1. json_data is empty"
                return False

            request = json_data_array[0]
            print "OneID authenticate for step 1. request: " + request

            if (StringHelper.isEmptyString(request)):
                return False
            
            authn.set_credentials()

            # Validate request
            http_client = httpService.getHttpsClientTrustAll();
            auth_data = httpService.encodeBase64(authn.api_id + ":" + authn.api_key)
            http_response = httpService.executePost(http_client, authn.helper_server + "/validate", auth_data, request, ContentType.APPLICATION_JSON)
            validation_content = httpService.convertEntityToString(httpService.getResponseContent(http_response))
            print "OneID authenticate for step 1. validation_content: " + validation_content
            
            if (StringHelper.isEmptyString(validation_content)):
                return False

            validation_resp = json.loads(validation_content)
            print "OneID authenticate for step 1. validation_resp: " + str(validation_resp)

            if (not authn.success(validation_resp)):
                return False

            response = json.loads(request)
            for x in validation_resp:
                response[x] = validation_resp[x]

            oneid_user_uid = response['uid']
            print "OneID authenticate for step 1. oneid_user_uid: " + oneid_user_uid

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

            if (find_user_by_uid == None):
                print "OneID authenticate for step 1. Failed to find user"
                print "OneID authenticate for step 1. Setting count steps to 2"
                context.set("oneid_count_login_steps", 2)
                context.set("oneid_user_uid", stringEncrypter.encrypt(oneid_user_uid))
                return True

            found_user_name = find_user_by_uid.getUserId()
            print "OneID authenticate for step 1. found_user_name: " + found_user_name

            credentials = Identity.instance().getCredentials()
            credentials.setUsername(found_user_name)
            credentials.setUser(find_user_by_uid)
            
            print "OneID authenticate for step 1. Setting count steps to 1"
            context.set("oneid_count_login_steps", 1)

            return True
        elif (step == 2):
            print "OneID authenticate for step 2"
            
            oneid_user_uid_array = requestParameters.get("oneid_user_uid")
            if ArrayHelper.isEmpty(oneid_user_uid_array):
                print "OneID authenticate for step 2. oneid_user_uid is empty"
                return False

            oneid_user_uid = stringEncrypter.decrypt(oneid_user_uid_array[0])
#
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            passed_step1 = StringHelper.isNotEmptyString(user_name)

            if (not passed_step1):
                return False
#
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

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

            if (find_user_by_uid == None):
                # Add oneid_user_uid to user one id UIDs
                find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "oneid:" + oneid_user_uid)
                if (find_user_by_uid == None):
                    print "OneID authenticate for step 2. Failed to update current user"
                    return False

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "OneID 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):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()
        httpService = HttpService.instance();

        stringEncrypter = StringEncrypter.defaultInstance()

        cas_host = configurationAttributes.get("cas_host").getValue2()
        cas_extra_opts = configurationAttributes.get("cas_extra_opts").getValue2()
        cas_map_user = StringHelper.toBoolean(configurationAttributes.get("cas_map_user").getValue2(), False)
        cas_renew_opt = StringHelper.toBoolean(configurationAttributes.get("cas_renew_opt").getValue2(), False)

        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
            request = FacesContext.getCurrentInstance().getExternalContext().getRequest()

            parametersMap = HashMap()
            parametersMap.put("service", httpService.constructServerUrl(request) + "/postlogin")
            if (cas_renew_opt):
                parametersMap.put("renew", "true")
            parametersMap.put("ticket", ticket)
            cas_service_request_uri = authenticationService.parametersAsString(parametersMap)
            cas_service_request_uri = cas_host + "/serviceValidate?" + cas_service_request_uri
            if StringHelper.isNotEmpty(cas_extra_opts):
                cas_service_request_uri = cas_service_request_uri + "&" + cas_extra_opts

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

            http_client = httpService.getHttpsClientTrustAll();
            http_response = httpService.executeGet(http_client, cas_service_request_uri)
            validation_content = httpService.convertEntityToString(httpService.getResponseContent(http_response))
            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 (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"
                    context.set("cas2_count_login_steps", 2)
                    context.set("cas2_user_uid", stringEncrypter.encrypt(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

                credentials = Identity.instance().getCredentials()
                credentials.setUsername(found_user_name)
                credentials.setUser(find_user_by_uid)
            
                print "CAS2 authenticate for step 1. Setting count steps to 1"
                context.set("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 the 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

                credentials = Identity.instance().getCredentials()
                credentials.setUsername(found_user_name)
                credentials.setUser(find_user_by_uid)

                print "CAS2 authenticate for step 1. Setting count steps to 1"
                context.set("cas2_count_login_steps", 1)

                return True
        elif (step == 2):
            print "CAS2 authenticate for step 2"
            
            cas2_user_uid_array = requestParameters.get("cas2_user_uid")
            if ArrayHelper.isEmpty(cas2_user_uid_array):
                print "CAS2 authenticate for step 2. cas2_user_uid is empty"
                return False

            cas2_user_uid = stringEncrypter.decrypt(cas2_user_uid_array[0])
            passed_step1 = StringHelper.isNotEmptyString(cas2_user_uid)
            if (not passed_step1):
                return False

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                logged_in = userService.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):
        context = Contexts.getEventContext()
        userService = UserService.instance()

        stringEncrypter = StringEncrypter.defaultInstance()

        oxpush_user_timeout = int(configurationAttributes.get("oxpush_user_timeout").getValue2())
        oxpush_application_name = configurationAttributes.get("oxpush_application_name").getValue2()

        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        if (step == 1):
            print "oxPush authenticate for step 1"

            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                userService = UserService.instance()
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            # Find user by uid
            userService = UserService.instance()
            find_user_by_uid = userService.getUser(user_name)
            if (find_user_by_uid == None):
                print "oxPush authenticate for step 1. Failed to find user"
                return False

            # Check if the user paired account to phone
            user_external_uid_attr = userService.getCustomAttribute(find_user_by_uid, "oxExternalUid")
            if ((user_external_uid_attr == None) or (user_external_uid_attr.getValues() == None)):
                print "oxPush authenticate for step 1. There is no external UIDs for user: "******"oxPush authenticate for step 1. There is no oxPush UID for user: "******"oxPush authenticate for step 1. oxpush_user_uid: ", oxpush_user_uid
                    deployment_status = self.oxPushClient.getDeploymentStatus(oxpush_user_uid); 
                    if (deployment_status.result):
                        print "oxPush authenticate for step 1. Deployment status is valid"
                        if ("enabled" == deployment_status.status):
                            print "oxPush authenticate for step 1. Deployment is enabled"
                            context.set("oxpush_user_uid", stringEncrypter.encrypt(oxpush_user_uid))
                        else:
                            print "oxPush authenticate for step 1. Deployment is disabled"
                            return False
                    else:
                        print "oxPush authenticate for step 1. Deployment status is invalid. Force user to pair again"
                        # Remove oxpush_user_uid from user entry
                        find_user_by_uid = userService.removeUserAttribute(user_name, "oxExternalUid", "oxpush:" + oxpush_user_uid)
                        if (find_user_by_uid == None):
                            print "oxPush authenticate for step 1. Failed to update current user"
                            return False

            return True
        elif (step == 2):
            print "oxPush authenticate for step 2"

            passed_step1 = self.isPassedDefaultAuthentication
            if (not passed_step1):
                return False

            oxpush_user_uid_array = requestParameters.get("oxpush_user_uid")
            if (ArrayHelper.isEmpty(oxpush_user_uid_array) or StringHelper.isEmptyString(oxpush_user_uid_array[0])):
                print "oxPush authenticate for step 2. oxpush_user_uid is empty"

                oxpush_pairing_uid_array = requestParameters.get("oxpush_pairing_uid")
                if (ArrayHelper.isEmpty(oxpush_pairing_uid_array) or StringHelper.isEmptyString(oxpush_pairing_uid_array[0])):
                    print "oxPush authenticate for step 2. oxpush_pairing_uid is empty"
                    return False

                oxpush_pairing_uid = stringEncrypter.decrypt(oxpush_pairing_uid_array[0])

                # Check pairing status                
                pairing_status = self.checkStatus("pair", oxpush_pairing_uid, oxpush_user_timeout)
                if (pairing_status == None):
                    print "oxPush authenticate for step 2. The pairing has not been authorized by user"
                    return False

                oxpush_user_uid = pairing_status.deploymentId

                print "oxPush authenticate for step 2. Storing oxpush_user_uid in user entry", oxpush_user_uid

                # Store oxpush_user_uid in user entry
                find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "oxpush:" + oxpush_user_uid)
                if (find_user_by_uid == None):
                    print "oxPush authenticate for step 2. Failed to update current user"
                    return False

                context.set("oxpush_count_login_steps", 2)
                context.set("oxpush_user_uid", stringEncrypter.encrypt(oxpush_user_uid))
            else:
                print "oxPush authenticate for step 2. Deployment status is valid"

            return True
        elif (step == 3):
            print "oxPush authenticate for step 3"

            passed_step1 = self.isPassedDefaultAuthentication
            if (not passed_step1):
                return False

            oxpush_user_uid_array = requestParameters.get("oxpush_user_uid")
            if ArrayHelper.isEmpty(oxpush_user_uid_array):
                print "oxPush authenticate for step 3. oxpush_user_uid is empty"
                return False

            oxpush_user_uid = stringEncrypter.decrypt(oxpush_user_uid_array[0])

            # Initialize authentication process
            authentication_request = None
            try:
                authentication_request = self.oxPushClient.authenticate(oxpush_user_uid, user_name);
            except java.lang.Exception, err:
                print "oxPush authenticate for step 3. Failed to initialize authentication process: ", err
                return False

            if (not authentication_request.result):
                print "oxPush authenticate for step 3. Failed to initialize authentication process"
                return False

            # Check authentication status                
            authentication_status = self.checkStatus("authenticate", authentication_request.authenticationId, oxpush_user_timeout)
            if (authentication_status == None):
                print "oxPush authenticate for step 3. The authentication has not been authorized by user"
                return False
                
            print "oxPush authenticate for step 3. The request was granted"

            return True
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()

        stringEncrypter = StringEncrypter.defaultInstance()

        saml_map_user = False
        saml_enroll_user = False
        saml_enroll_all_user_attr = False
        # Use saml_deployment_type only if there is no attributes mapping
        if (configurationAttributes.containsKey("saml_deployment_type")):
            saml_deployment_type = StringHelper.toLowerCase(configurationAttributes.get("saml_deployment_type").getValue2())
            
            if (StringHelper.equalsIgnoreCase(saml_deployment_type, "map")):
                saml_map_user = True

            if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll")):
                saml_enroll_user = True

            if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll_all_attr")):
                saml_enroll_all_user_attr = True

        saml_allow_basic_login = False
        if (configurationAttributes.containsKey("saml_allow_basic_login")):
            saml_allow_basic_login = StringHelper.toBoolean(configurationAttributes.get("saml_allow_basic_login").getValue2(), False)

        use_basic_auth = False
        if (saml_allow_basic_login):
            basic_auth = requestParameters.get("basic_auth")
            if (ArrayHelper.isNotEmpty(basic_auth)):
                use_basic_auth = StringHelper.toBoolean(basic_auth[0], False)

        if ((step == 1) and saml_allow_basic_login and use_basic_auth):
            print "Saml authenticate for step 1. Basic authentication"

            context.set("saml_count_login_steps", 1)

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                userService = UserService.instance()
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            return True

        if (step == 1):
            print "Saml authenticate for step 1"

            currentSamlConfiguration = self.getCurrentSamlConfiguration(self.samlConfiguration, configurationAttributes, requestParameters)
            if (currentSamlConfiguration == None):
                print "Saml prepare for step 1. Client saml configuration is invalid"
                return False

            saml_response_array = requestParameters.get("SAMLResponse")
            if ArrayHelper.isEmpty(saml_response_array):
                print "Saml authenticate for step 1. saml_response is empty"
                return False

            saml_response = saml_response_array[0]

            print "Saml authenticate for step 1. saml_response:", saml_response

            samlResponse = Response(currentSamlConfiguration)
            samlResponse.loadXmlFromBase64(saml_response)
            
            saml_validate_response = True
            if (configurationAttributes.containsKey("saml_validate_response")):
                saml_validate_response = StringHelper.toBoolean(configurationAttributes.get("saml_validate_response").getValue2(), False)

            if (saml_validate_response):
                if (not samlResponse.isValid()):
                    print "Saml authenticate for step 1. saml_response isn't valid"

            saml_response_name_id = samlResponse.getNameId()
            if (StringHelper.isEmpty(saml_response_name_id)):
                print "Saml authenticate for step 1. saml_response_name_id is invalid"
                return False

            print "Saml authenticate for step 1. saml_response_name_id:", saml_response_name_id

            saml_response_attributes = samlResponse.getAttributes()
            print "Saml authenticate for step 1. attributes: ", saml_response_attributes

            # Use persistent Id as saml_user_uid
            saml_user_uid = saml_response_name_id
            
            if (saml_map_user):
                # Use mapping to local IDP user
                print "Saml authenticate for step 1. Attempting to find user by oxExternalUid: saml:", saml_user_uid

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

                if (find_user_by_uid == None):
                    print "Saml authenticate for step 1. Failed to find user"
                    print "Saml authenticate for step 1. Setting count steps to 2"
                    context.set("saml_count_login_steps", 2)
                    context.set("saml_user_uid", stringEncrypter.encrypt(saml_user_uid))
                    return True

                found_user_name = find_user_by_uid.getUserId()
                print "Saml authenticate for step 1. found_user_name:", found_user_name
                
                user_authenticated = authenticationService.authenticate(found_user_name)
                if (user_authenticated == False):
                    print "Saml authenticate for step 1. Failed to authenticate user"
                    return False
            
                print "Saml authenticate for step 1. Setting count steps to 1"
                context.set("saml_count_login_steps", 1)

                post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid)
                print "Saml authenticate for step 1. post_login_result:", post_login_result

                return post_login_result
            elif (saml_enroll_user):
                # Use auto enrollment to local IDP
                print "Saml authenticate for step 1. Attempting to find user by oxExternalUid: saml:", saml_user_uid

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

                if (find_user_by_uid == None):
                    # Auto user enrollemnt
                    print "Saml authenticate for step 1. There is no user in LDAP. Adding user to local LDAP"

                    # Convert saml result attributes keys to lover case
                    saml_response_normalized_attributes = HashMap()
                    for saml_response_attribute_entry in saml_response_attributes.entrySet():
                        saml_response_normalized_attributes.put(
                            StringHelper.toLowerCase(saml_response_attribute_entry.getKey()), saml_response_attribute_entry.getValue())

                    currentAttributesMapping = self.prepareCurrentAttributesMapping(self.attributesMapping, configurationAttributes, requestParameters)
                    print "Saml authenticate for step 1. Using next attributes mapping", currentAttributesMapping

                    newUser = User()
                    for attributesMappingEntry in currentAttributesMapping.entrySet():
                        idpAttribute = attributesMappingEntry.getKey()
                        localAttribute = attributesMappingEntry.getValue()

                        localAttributeValue = saml_response_normalized_attributes.get(idpAttribute)
                        if (localAttribute != None):
                            newUser.setAttribute(localAttribute, localAttributeValue)

                    newUser.setAttribute("oxExternalUid", "saml:" + saml_user_uid)
                    print "Saml authenticate for step 1. Attempting to add user", saml_user_uid, " with next attributes", newUser.getCustomAttributes()

                    find_user_by_uid = userService.addUser(newUser)
                    print "Saml authenticate for step 1. Added new user with UID", find_user_by_uid.getUserId()
            elif (saml_enroll_all_user_attr):
                print "Saml authenticate for step 1. Attempting to find user by oxExternalUid: saml:" + saml_user_uid

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

                if (find_user_by_uid == None):
                    print "Saml authenticate for step 1. Failed to find user"

                    user = User()
                    customAttributes = ArrayList()
                    for key in attributes.keySet():
                        ldapAttributes = attributeService.getAllAttributes()
                        for ldapAttribute in ldapAttributes:
                            saml2Uri = ldapAttribute.getSaml2Uri()
                            if(saml2Uri == None):
                                saml2Uri = attributeService.getDefaultSaml2Uri(ldapAttribute.getName())
                            if(saml2Uri == key):
                                attribute = CustomAttribute(ldapAttribute.getName())
                                attribute.setValues(attributes.get(key))
                                customAttributes.add(attribute)

                    attribute = CustomAttribute("oxExternalUid")
                    attribute.setValue("saml:" + saml_user_uid)
                    customAttributes.add(attribute)
                    user.setCustomAttributes(customAttributes)

                    if(user.getAttribute("sn") == None):
                        attribute = CustomAttribute("sn")
                        attribute.setValue(saml_user_uid)
                        customAttributes.add(attribute)

                    if(user.getAttribute("cn") == None):
                        attribute = CustomAttribute("cn")
                        attribute.setValue(saml_user_uid)
                        customAttributes.add(attribute)

                    find_user_by_uid = userService.addUser(user)
                    print "Saml authenticate for step 1. Added new user with UID", find_user_by_uid.getUserId()

                found_user_name = find_user_by_uid.getUserId()
                print "Saml authenticate for step 1. found_user_name:", found_user_name

                user_authenticated = authenticationService.authenticate(found_user_name)
                if (user_authenticated == False):
                    print "Saml authenticate for step 1. Failed to authenticate user"
                    return False

                print "Saml authenticate for step 1. Setting count steps to 1"
                context.set("saml_count_login_steps", 1)

                post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid)
                print "Saml authenticate for step 1. post_login_result:", post_login_result

                return post_login_result
            else:
                # Check if the is user with specified saml_user_uid
                print "Saml authenticate for step 1. Attempting to find user by uid:", saml_user_uid

                find_user_by_uid = userService.getUser(saml_user_uid)
                if (find_user_by_uid == None):
                    print "Saml authenticate for step 1. Failed to find user"
                    return False

                found_user_name = find_user_by_uid.getUserId()
                print "Saml authenticate for step 1. found_user_name:", found_user_name

                user_authenticated = authenticationService.authenticate(found_user_name)
                if (user_authenticated == False):
                    print "Saml authenticate for step 1. Failed to authenticate user"
                    return False

                print "Saml authenticate for step 1. Setting count steps to 1"
                context.set("saml_count_login_steps", 1)

                post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid)
                print "Saml authenticate for step 1. post_login_result:", post_login_result

                return post_login_result
        elif (step == 2):
            print "Saml authenticate for step 2"
            
            saml_user_uid_array = requestParameters.get("saml_user_uid")
            if ArrayHelper.isEmpty(saml_user_uid_array):
                print "Saml authenticate for step 2. saml_user_uid is empty"
                return False

            saml_user_uid = stringEncrypter.decrypt(saml_user_uid_array[0])
            passed_step1 = StringHelper.isNotEmptyString(saml_user_uid)
            if (not passed_step1):
                return False

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

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

            if (not logged_in):
                return False

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

            if (find_user_by_uid == None):
                # Add saml_user_uid to user one id UIDs
                find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "saml:" + saml_user_uid)
                if (find_user_by_uid == None):
                    print "Saml authenticate for step 2. Failed to update current user"
                    return False

                post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid)
                print "Saml authenticate for step 2. post_login_result:", post_login_result

                return post_login_result
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "Saml authenticate for step 2. found_user_name:", found_user_name
    
                if StringHelper.equals(user_name, found_user_name):
                    post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid)
                    print "Saml authenticate for step 2. post_login_result:", post_login_result
    
                    return post_login_result
        
            return False
        else:
            return False