def init(self, configurationAttributes):
        print "Basic (lock account). Initialization"

        self.invalidLoginCountAttribute = "oxCountInvalidLogin"
        if configurationAttributes.containsKey(
                "invalid_login_count_attribute"):
            self.invalidLoginCountAttribute = configurationAttributes.get(
                "invalid_login_count_attribute").getValue2()
        else:
            print "Basic (lock account). Initialization. Using default attribute"

        self.maximumInvalidLoginAttemps = 3
        if configurationAttributes.containsKey(
                "maximum_invalid_login_attemps"):
            self.maximumInvalidLoginAttemps = StringHelper.toInteger(
                configurationAttributes.get(
                    "maximum_invalid_login_attemps").getValue2())
        else:
            print "Basic (lock account). Initialization. Using default number attempts"

        self.lockExpirationTime = 180
        if configurationAttributes.containsKey("lock_expiration_time"):
            self.lockExpirationTime = StringHelper.toInteger(
                configurationAttributes.get(
                    "lock_expiration_time").getValue2())
        else:
            print "Basic (lock account). Initialization. Using default lock expiration time"

        print "Basic (lock account). Initialized successfully. invalid_login_count_attribute: '%s', maximum_invalid_login_attemps: '%s'" % (
            self.invalidLoginCountAttribute, self.maximumInvalidLoginAttemps)

        return True
    def authenticate(self, configurationAttributes, requestParameters, step):
        if step == 1:
            print "Basic (lock account). Authenticate for step 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 = Component.getInstance(UserService)
                try:
                    logged_in = userService.authenticate(user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if (not logged_in):
                countInvalidLoginArributeValue = self.getUserAttributeValue(user_name, self.invalidLoginCountAttribute)
                countInvalidLogin = StringHelper.toInteger(countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(countInvalidLogin))

                if countInvalidLogin >= self.maximumInvalidLoginAttemps:
                    self.lockUser(user_name)
                    
                return False

            self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(0))

            return True
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        if step == 1:
            print "Basic (lock account). Authenticate for step 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()
                try:
                    logged_in = userService.authenticate(user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if (not logged_in):
                countInvalidLoginArributeValue = self.getUserAttributeValue(user_name, self.invalidLoginCountAttribute)
                countInvalidLogin = StringHelper.toInteger(countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(countInvalidLogin))

                if countInvalidLogin >= self.maximumInvalidLoginAttemps:
                    self.lockUser(user_name)
                    
                return False

            self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(0))

            return True
        else:
            return False
Example #4
0
    def getCountAuthenticationSteps(self, configurationAttributes):
        identity = CdiUtil.bean(Identity)

        if identity.isSetWorkingParameter("otp_count_login_steps"):
            return StringHelper.toInteger(
                "%s" % identity.getWorkingParameter("otp_count_login_steps"))
        else:
            return 2
Example #5
0
    def getCountAuthenticationSteps(self, configurationAttributes):
        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        if session_attributes.containsKey("otp_count_login_steps"):
            return StringHelper.toInteger(session_attributes.get("otp_count_login_steps"))
        else:
            return 2
Example #6
0
    def getCountAuthenticationSteps(self, configurationAttributes):
        identity = CdiUtil.bean(Identity)
        session_attributes = identity.getSessionId().getSessionAttributes()

        if session_attributes.containsKey("otp_count_login_steps"):
            return StringHelper.toInteger(session_attributes.get("otp_count_login_steps"))
        else:
            return 2
    def getCountAuthenticationSteps(self, configurationAttributes):
        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        if session_attributes.containsKey("otp_count_login_steps"):
            return StringHelper.toInteger(session_attributes.get("otp_count_login_steps"))
        else:
            return 2
    def init(self, configurationAttributes):
        print "Cert. Initialization"

        if not (configurationAttributes.containsKey("chain_cert_file_path")):
            print "Cert. Initialization. Property chain_cert_file_path is mandatory"
            return False

        if not (configurationAttributes.containsKey("map_user_cert")):
            print "Cert. Initialization. Property map_user_cert is mandatory"
            return False

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

        self.chain_certs = CertUtil.loadX509CertificateFromFile(
            chain_cert_file_path)
        print "Cert. Initialization. Loaded '%d' chain certificates" % self.chain_certs.size(
        )

        crl_max_response_size = 5 * 1024 * 1024  # 10Mb
        if configurationAttributes.containsKey("crl_max_response_size"):
            crl_max_response_size = StringHelper.toInteger(
                configurationAttributes.get(
                    "crl_max_response_size").getValue2(),
                crl_max_response_size)
            print "Cert. Initialization. CRL max response size is '%d'" % crl_max_response_size

        # Define array to order methods correctly
        self.validator_types = ['generic', 'path', 'ocsp', 'crl']
        self.validators = {
            'generic': [GenericCertificateVerifier(), False],
            'path': [PathCertificateVerifier(False), False],
            'ocsp': [OCSPCertificateVerifier(), False],
            'crl': [CRLCertificateVerifier(crl_max_response_size), False]
        }

        for type in self.validator_types:
            validator_param_name = "use_%s_validator" % type
            if configurationAttributes.containsKey(validator_param_name):
                validator_status = StringHelper.toBoolean(
                    configurationAttributes.get(
                        validator_param_name).getValue2(), False)
                self.validators[type][1] = validator_status

            print "Cert. Initialization. Validation method '%s' status: '%s'" % (
                type, self.validators[type][1])

        self.map_user_cert = StringHelper.toBoolean(
            configurationAttributes.get("map_user_cert").getValue2(), False)
        print "Cert. Initialization. map_user_cert: '%s'" % self.map_user_cert

        self.enabled_recaptcha = self.initRecaptcha(configurationAttributes)
        print "Cert. Initialization. enabled_recaptcha: '%s'" % self.enabled_recaptcha

        print "Cert. Initialized successfully"

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

        if not (configurationAttributes.containsKey("chain_cert_file_path")):
            print "Cert. Initialization. Property chain_cert_file_path is mandatory"
            return False

        if not (configurationAttributes.containsKey("map_user_cert")):
            print "Cert. Initialization. Property map_user_cert is mandatory"
            return False

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

        self.chain_certs = CertUtil.loadX509CertificateFromFile(chain_cert_file_path)
        print "Cert. Initialization. Loaded '%d' chain certificates" % self.chain_certs.size()
        
        crl_max_response_size = 5 * 1024 * 1024  # 10Mb
        if configurationAttributes.containsKey("crl_max_response_size"):
            crl_max_response_size = StringHelper.toInteger(configurationAttributes.get("crl_max_response_size").getValue2(), crl_max_response_size)
            print "Cert. Initialization. CRL max response size is '%d'" % crl_max_response_size

        # Define array to order methods correctly
        self.validator_types = [ 'generic', 'path', 'ocsp', 'crl']
        self.validators = { 'generic' : [GenericCertificateVerifier(), False],
                            'path' : [PathCertificateVerifier(False), False],
                            'ocsp' : [OCSPCertificateVerifier(), False],
                            'crl' : [CRLCertificateVerifier(crl_max_response_size), False] }

        for type in self.validator_types:
            validator_param_name = "use_%s_validator" % type
            if configurationAttributes.containsKey(validator_param_name):
                validator_status = StringHelper.toBoolean(configurationAttributes.get(validator_param_name).getValue2(), False)
                self.validators[type][1] = validator_status

            print "Cert. Initialization. Validation method '%s' status: '%s'" % (type, self.validators[type][1])

        self.map_user_cert = StringHelper.toBoolean(configurationAttributes.get("map_user_cert").getValue2(), False)
        print "Cert. Initialization. map_user_cert: '%s'" % self.map_user_cert

        self.enabled_recaptcha = self.initRecaptcha(configurationAttributes)
        print "Cert. Initialization. enabled_recaptcha: '%s'" % self.enabled_recaptcha

        print "Cert. Initialized successfully"

        return True   
    def init(self, configurationAttributes):
        print "Basic (lock account). Initialization"

        self.invalidLoginCountAttribute = "oxCountInvalidLogin"
        if configurationAttributes.containsKey("invalid_login_count_attribute"):
            self.invalidLoginCountAttribute = configurationAttributes.get("invalid_login_count_attribute").getValue2()
        else:
            print "Basic (lock account). Initialization. Using default attribute"

        self.maximumInvalidLoginAttemps = 3
        if configurationAttributes.containsKey("maximum_invalid_login_attemps"):
            self.maximumInvalidLoginAttemps = StringHelper.toInteger(configurationAttributes.get("maximum_invalid_login_attemps").getValue2())
        else:
            print "Basic (lock account). Initialization. Using default number attempts"

        print "Basic (lock account). Initialized successfully. invalid_login_count_attribute: '%s', maximum_invalid_login_attemps: '%s'" % (self.invalidLoginCountAttribute, self.maximumInvalidLoginAttemps)

        return True   
    def init(self, configurationAttributes):
        print("Basic (multi auth conf & lock account). Initialization")

        if (not configurationAttributes.containsKey("auth_configuration_file")):
            print("Basic (multi auth conf & lock account). The property auth_configuration_file is empty")
            return False

        self.invalidLoginCountAttribute = "oxCountInvalidLogin"
        if configurationAttributes.containsKey("invalid_login_count_attribute"):
            self.invalidLoginCountAttribute = configurationAttributes.get(
                "invalid_login_count_attribute").getValue2()
        else:
            print("Basic (multi auth conf & lock account). Initialization. Using default attribute")

        self.maximumInvalidLoginAttemps = 3
        if configurationAttributes.containsKey("maximum_invalid_login_attemps"):
            self.maximumInvalidLoginAttemps = StringHelper.toInteger(
                configurationAttributes.get("maximum_invalid_login_attemps").getValue2())
        else:
            print("Basic (multi auth conf & lock account). Initialization. Using default number attempts")

        authConfigurationFile = configurationAttributes.get(
            "auth_configuration_file").getValue2()
        authConfiguration = self.loadAuthConfiguration(authConfigurationFile)
        if authConfiguration is None:
            print("Basic (multi auth conf & lock account). File with authentication configuration should be not empty")
            return False

        validationResult = self.validateAuthConfiguration(authConfiguration)
        if (not validationResult):
            return False

        ldapExtendedEntryManagers = self.createLdapExtendedEntryManagers(
            authConfiguration)
        if ldapExtendedEntryManagers is None:
            return False

        self.ldapExtendedEntryManagers = ldapExtendedEntryManagers

        print("Basic (multi auth conf & lock account). Initialized successfully")
        return True
Example #12
0
    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):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Basic (lock account). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            cacheService = CdiUtil.bean(CacheService)
            userService = CdiUtil.bean(UserService)

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                try:
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if not logged_in:
                countInvalidLoginArributeValue = self.getUserAttributeValue(
                    user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user status %s" % userSatus
                countInvalidLogin = StringHelper.toInteger(
                    countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin
                    print "Remainings counts %s" % remainingAttempts
                    self.setUserAttributeValue(
                        user_name, self.invalidLoginCountAttribute,
                        StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(
                            FacesMessage.SEVERITY_INFO,
                            StringHelper.toString(remainingAttempts) +
                            " more attempt(s) before account is LOCKED!")

                if countInvalidLogin >= self.maximumInvalidLoginAttemps:
                    self.lockUser(user_name, self.maximumInvalidLoginAttemps)
                    return False

                object_from_store = cacheService.get(None,
                                                     "lock_user_" + user_name)
                if object_from_store == None and countInvalidLogin >= self.maximumInvalidLoginAttemps:
                    print "Basic (lock account).Lock Expired for '%s'" % user_name
                    self.unLockUser(user_name)
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)
                    return True
                elif object_from_store != None:
                    print "Basic (lock account). Lock Expiration time is ACTIVE for user '%s'" % user_name

                return False

            self.setUserAttributeValue(user_name,
                                       self.invalidLoginCountAttribute,
                                       StringHelper.toString(0))

            return True
        else:
            return False
    def processOtpAuthentication(self, requestParameters, user_name, session_attributes, otp_auth_method):
        facesMessages = FacesMessages.instance()
        FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True)

        userService = UserService.instance()

        otpCode = ServerUtil.getFirstValue(requestParameters, "loginForm:otpCode")
        if StringHelper.isEmpty(otpCode):
            facesMessages.add(StatusMessage.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 = session_attributes.get("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(StatusMessage.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(StatusMessage.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):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Basic (lock account). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            cacheService = CdiUtil.bean(CacheService)
            userService = CdiUtil.bean(UserService)

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                try:
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if not logged_in:
                countInvalidLoginArributeValue = self.getUserAttributeValue(
                    user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user '%s' status is '%s'" % (user_name,
                                                            userSatus)

                countInvalidLogin = StringHelper.toInteger(
                    countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin

                    print "Remaining login count attempts '%s' for user '%s'" % (
                        remainingAttempts, user_name)

                    self.setUserAttributeValue(
                        user_name, self.invalidLoginCountAttribute,
                        StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(
                            FacesMessage.SEVERITY_INFO,
                            StringHelper.toString(remainingAttempts) +
                            " more attempt(s) before account is LOCKED!")

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and (
                    (userSatus == None) or (userSatus == "active")):
                    print "Basic (lock account). Locking '%s' for '%s' seconds" % (
                        user_name, self.lockExpirationTime)
                    self.lockUser(user_name)
                    return False

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps
                    ) and userSatus == "inactive":
                    print "Basic (lock account). User '%s' is locked. Checking if we can unlock him" % user_name

                    unlock_and_authenticate = False

                    object_from_store = cacheService.get(
                        None, "lock_user_" + user_name)
                    if object_from_store == None:
                        # Object in cache was expired. We need to unlock user
                        print "Basic (lock account). User locking details for user '%s' not exists" % user_name
                        unlock_and_authenticate = True
                    else:
                        # Analyze object from cache
                        user_lock_details = json.loads(object_from_store)

                        user_lock_details_locked = user_lock_details['locked']
                        user_lock_details_created = user_lock_details[
                            'created']
                        user_lock_details_created_date = LocalDateTime.parse(
                            user_lock_details_created,
                            DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        user_lock_details_created_diff = Duration.between(
                            user_lock_details_created_date,
                            LocalDateTime.now()).getSeconds()
                        print "Basic (lock account). Get user '%s' locking details. locked: '%s', Created: '%s', Difference in seconds: '%s'" % (
                            user_name, user_lock_details_locked,
                            user_lock_details_created,
                            user_lock_details_created_diff)

                        if user_lock_details_locked and user_lock_details_created_diff >= self.lockExpirationTime:
                            print "Basic (lock account). Unlocking user '%s' after lock expiration" % user_name
                            unlock_and_authenticate = True

                    if unlock_and_authenticate:
                        self.unLockUser(user_name)
                        self.setUserAttributeValue(
                            user_name, self.invalidLoginCountAttribute,
                            StringHelper.toString(0))
                        logged_in = authenticationService.authenticate(
                            user_name, user_password)
                        if not logged_in:
                            # Update number of attempts
                            self.setUserAttributeValue(
                                user_name, self.invalidLoginCountAttribute,
                                StringHelper.toString(1))
                            if self.maximumInvalidLoginAttemps == 1:
                                # Lock user if maximum count login attempts is 1
                                self.lockUser(user_name)
                                return False

            return logged_in
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print("Basic (multi auth conf & lock account). Authenticate for step 1")

            credentials = Identity.instance().getCredentials()
            keyValue = credentials.getUsername()
            userPassword = credentials.getPassword()

            if not StringHelper.isNotEmptyString(keyValue) or not StringHelper.isNotEmptyString(userPassword):
                print("Basic (multi auth conf & lock account). Missing fields ")
                faces_messages = FacesMessages.instance()
                faces_messages.clear()
                FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True)
                faces_messages.addFromResourceBundle(
                    FacesMessage.SEVERITY_ERROR, "login.missingField")
                return False

            keyValue = keyValue.strip()

            user_status = self.getUserAttributeValue(keyValue, "gluuStatus")
            if user_status is not None and user_status != "active":
                print("Basic (multi auth conf & lock account). Account locked for user '%s'" % keyValue)
                faces_messages = FacesMessages.instance()
                faces_messages.clear()
                FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True)
                faces_messages.addFromResourceBundle(
                    FacesMessage.SEVERITY_ERROR, "login.accountLocked")
                return False

            if (StringHelper.isNotEmptyString(keyValue) and StringHelper.isNotEmptyString(userPassword)):
                authenticationService = Component.getInstance(
                    AuthenticationService)

                logged_in = False
                for ldapExtendedEntryManager in self.ldapExtendedEntryManagers:
                    if logged_in:
                        break

                    ldapConfiguration = ldapExtendedEntryManager["ldapConfiguration"]
                    ldapEntryManager = ldapExtendedEntryManager["ldapEntryManager"]
                    loginAttributes = ldapExtendedEntryManager["loginAttributes"]
                    localLoginAttributes = ldapExtendedEntryManager["localLoginAttributes"]

                    print("Basic (multi auth conf & lock account). Authenticate for step 1. Using configuration: " +
                          ldapConfiguration.getConfigId())

                    idx = 0
                    count = len(loginAttributes)
                    while (idx < count):
                        primaryKey = loginAttributes[idx]
                        localPrimaryKey = localLoginAttributes[idx]

                        loggedIn = authenticationService.authenticate(
                            ldapConfiguration, ldapEntryManager, keyValue, userPassword, primaryKey, localPrimaryKey)
                        if (loggedIn):
                            logged_in = True
                            break
                        idx += 1

                if logged_in:
                    self.setUserAttributeValue(
                        keyValue, self.invalidLoginCountAttribute, StringHelper.toString(0))

                    return True

                countInvalidLoginArributeValue = self.getUserAttributeValue(
                    keyValue, self.invalidLoginCountAttribute)
                countInvalidLogin = StringHelper.toInteger(
                    countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    self.setUserAttributeValue(
                        keyValue, self.invalidLoginCountAttribute, StringHelper.toString(countInvalidLogin))

                if countInvalidLogin >= self.maximumInvalidLoginAttemps:
                    self.lockUser(keyValue)
                    self.setUserAttributeValue(
                        keyValue, self.invalidLoginCountAttribute, StringHelper.toString(0))

            return False
        else:
            return False