def prepareAttributesMapping(self, saml_idp_attributes_list, saml_local_attributes_list):
        saml_idp_attributes_list_array = StringHelper.split(saml_idp_attributes_list, ",")
        if (ArrayHelper.isEmpty(saml_idp_attributes_list_array)):
            print "Saml. PrepareAttributesMapping. There is no attributes specified in saml_idp_attributes_list property"
            return None
        
        saml_local_attributes_list_array = StringHelper.split(saml_local_attributes_list, ",")
        if (ArrayHelper.isEmpty(saml_local_attributes_list_array)):
            print "Saml. PrepareAttributesMapping. There is no attributes specified in saml_local_attributes_list property"
            return None

        if (len(saml_idp_attributes_list_array) != len(saml_local_attributes_list_array)):
            print "Saml. PrepareAttributesMapping. The number of attributes in saml_idp_attributes_list and saml_local_attributes_list isn't equal"
            return None
        
        attributeMapping = IdentityHashMap()
        containsUid = False
        i = 0
        count = len(saml_idp_attributes_list_array)
        while (i < count):
            idpAttribute = StringHelper.toLowerCase(saml_idp_attributes_list_array[i])
            localAttribute = StringHelper.toLowerCase(saml_local_attributes_list_array[i])
            attributeMapping.put(idpAttribute, localAttribute)

            if (StringHelper.equalsIgnoreCase(localAttribute, "uid")):
                containsUid = True

            i = i + 1

        if (not containsUid):
            print "Saml. PrepareAttributesMapping. There is no mapping to mandatory 'uid' attribute"
            return None
        
        return attributeMapping
    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
    def authenticate(self, configurationAttributes, requestParameters, step):
        duo_host = configurationAttributes.get("duo_host").getValue2()

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

        if (step == 1):
            print "Duo. 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

            authenticationService = AuthenticationService.instance()
            user = authenticationService.getAuthenticatedUser()
            if (self.use_duo_group):
                print "Duo. Authenticate for step 1. Checking if user belong to Duo group"
                is_member_duo_group = self.isUserMemberOfGroup(user, self.audit_attribute, self.duo_group)
                if (is_member_duo_group):
                    print "Duo. Authenticate for step 1. User '" + user.getUserId() + "' member of Duo group"
                    duo_count_login_steps = 2
                else:
                    self.processAuditGroup(user)
                    duo_count_login_steps = 1

                context = Contexts.getEventContext()
                context.set("duo_count_login_steps", duo_count_login_steps)

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

            sig_response_array = requestParameters.get("sig_response")
            if ArrayHelper.isEmpty(sig_response_array):
                print "Duo. Authenticate for step 2. sig_response is empty"
                return False

            duo_sig_response = sig_response_array[0]

            print "Duo. Authenticate for step 2. duo_sig_response: " + duo_sig_response

            authenticated_username = duo_web.verify_response(self.ikey, self.skey, self.akey, duo_sig_response)

            print "Duo. Authenticate for step 2. authenticated_username: "******", expected user_name: " + user_name

            if (not StringHelper.equals(user_name, authenticated_username)):
                return False

            authenticationService = AuthenticationService.instance()
            user = authenticationService.getAuthenticatedUser()
            self.processAuditGroup(user)

            return True
        else:
            return False
    def init(self, configurationAttributes):
        print "Basic (multi login) initialization"

        login_attributes_list_object = configurationAttributes.get("login_attributes_list")
        if (login_attributes_list_object == None):
            print "Basic (multi login) initialization. There is no property login_attributes_list"
            return False

        login_attributes_list = login_attributes_list_object.getValue2()
        if (StringHelper.isEmpty(login_attributes_list)):
            print "Basic (multi login) initialization. There is no attributes specified in login_attributes property"
            return False
        
        login_attributes_list_array = StringHelper.split(login_attributes_list, ",")
        if (ArrayHelper.isEmpty(login_attributes_list_array)):
            print "Basic (multi login) initialization. There is no attributes specified in login_attributes property"
            return False

        if (configurationAttributes.containsKey("local_login_attributes_list")):
            local_login_attributes_list = configurationAttributes.get("local_login_attributes_list").getValue2()
            local_login_attributes_list_array = StringHelper.split(local_login_attributes_list, ",")
        else:
            print "Basic (multi login) initialization. There is no property local_login_attributes_list. Assuming that login attributes are equal to local login attributes."
            local_login_attributes_list_array = login_attributes_list_array

        if (len(login_attributes_list_array) != len(local_login_attributes_list_array)):
            print "Basic (multi login) initialization. The number of attributes in login_attributes_list and local_login_attributes_list isn't equal"
            return False
        
        self.login_attributes_list_array = login_attributes_list_array
        self.local_login_attributes_list_array = local_login_attributes_list_array

        print "Basic (multi login) initialized successfully"
        return True   
    def authenticate(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print "Basic 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()
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False
# Commented out becuase we do the same in AuthenticationService.authenticate method
#
#            user = userService.getUser(user_name)
#            if (user == None):
#                print "Basic authenticate for step 1. Failed to find user in local LDAP"
#                return False
#
#            # Store user to allow use this module for web services 
#            credentials.setUser(user);

            return True
        else:
            return False
    def prepareAttributesMapping(self, remoteAttributesList, localAttributesList):
        remoteAttributesListArray = StringHelper.split(remoteAttributesList, ",")
        if (ArrayHelper.isEmpty(remoteAttributesListArray)):
            print "Google+ PrepareAttributesMapping. There is no attributes specified in remoteAttributesList property"
            return None
        
        localAttributesListArray = StringHelper.split(localAttributesList, ",")
        if (ArrayHelper.isEmpty(localAttributesListArray)):
            print "Google+ PrepareAttributesMapping. There is no attributes specified in localAttributesList property"
            return None

        if (len(remoteAttributesListArray) != len(localAttributesListArray)):
            print "Google+ PrepareAttributesMapping. The number of attributes in remoteAttributesList and localAttributesList isn't equal"
            return None
        
        attributeMapping = IdentityHashMap()
        containsUid = False
        i = 0
        count = len(remoteAttributesListArray)
        while (i < count):
            remoteAttribute = StringHelper.toLowerCase(remoteAttributesListArray[i])
            localAttribute = StringHelper.toLowerCase(localAttributesListArray[i])
            attributeMapping.put(remoteAttribute, localAttribute)

            if (StringHelper.equalsIgnoreCase(localAttribute, "uid")):
                containsUid = True

            i = i + 1

        if (not containsUid):
            print "Google+ PrepareAttributesMapping. There is no mapping to mandatory 'uid' attribute"
            return None
        
        return attributeMapping
    def authenticate(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print "Basic (multi login) authenticate for step 1"

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

            logged_in = False
            if (StringHelper.isNotEmptyString(key_value) and StringHelper.isNotEmptyString(user_password)):
                authenticationService = AuthenticationService.instance()

                i = 0;
                count = len(self.login_attributes_list_array)
                while (i < count):
                    primary_key = self.login_attributes_list_array[i]
                    local_primary_key = self.local_login_attributes_list_array[i]
                    logged_in = authenticationService.authenticate(key_value, user_password, primary_key, local_primary_key)
                    if (logged_in):
                        return True
                    i += 1

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print "Basic (multi auth conf) authenticate for step 1"

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

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

                for ldapExtendedEntryManager in self.ldapExtendedEntryManagers:
                    ldapConfiguration = ldapExtendedEntryManager["ldapConfiguration"]
                    ldapEntryManager = ldapExtendedEntryManager["ldapEntryManager"]
                    loginAttributes = ldapExtendedEntryManager["loginAttributes"]
                    localLoginAttributes = ldapExtendedEntryManager["localLoginAttributes"]

                    print "Basic (multi auth conf) 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):
                            return True
                        idx += 1

            return False
        else:
            return False
    def init(self, configurationAttributes):
        print "oxPush2. Initialization"

        if not (configurationAttributes.containsKey("application_id") and
                configurationAttributes.containsKey("authentication_mode")):
            print "oxPush2. Initialization. Properties application_id and authentication_mode are mandatory"
            return False

        self.application_id = configurationAttributes.get("application_id").getValue2()
        if StringHelper.isEmpty(self.application_id):
            print "oxPush2. Initialization. Failed to determine application_id. application_id configuration parameter is empty"
            return False

        authentication_mode = configurationAttributes.get("authentication_mode").getValue2()
        if StringHelper.isEmpty(authentication_mode):
            print "oxPush2. Initialization. Failed to determine authentication_mode. authentication_mode configuration parameter is empty"
            return False
        
        self.oneStep = StringHelper.equalsIgnoreCase(authentication_mode, "one_step")
        self.twoStep = StringHelper.equalsIgnoreCase(authentication_mode, "two_step")

        if not (self.oneStep or self.twoStep):
            print "oxPush2. Initialization. Valid authentication_mode values are one_step and two_step"
            return False
        
        self.enabledPushNotifications = self.initPushNotificationService(configurationAttributes)

        print "oxPush2. Initialized successfully. oneStep: '%s', twoStep: '%s', pushNotifications: '%s'" % (self.oneStep, self.twoStep, self.enabledPushNotifications)

        return True   
    def init(self, configurationAttributes):
        print "Passport: Basic. Initialization init method call"
        self.extensionModule = None
        self.attributesMapping = None
        if (configurationAttributes.containsKey("generic_remote_attributes_list") and
                configurationAttributes.containsKey("generic_local_attributes_list")):

            remoteAttributesList = configurationAttributes.get("generic_remote_attributes_list").getValue2()
            if (StringHelper.isEmpty(remoteAttributesList)):
                print "Passport: Initialization. The property generic_remote_attributes_list is empty"
                return False

            localAttributesList = configurationAttributes.get("generic_local_attributes_list").getValue2()
            if (StringHelper.isEmpty(localAttributesList)):
                print "Passport: Initialization. The property generic_local_attributes_list is empty"
                return False

            self.attributesMapping = self.prepareAttributesMapping(remoteAttributesList, localAttributesList)
            if (self.attributesMapping == None):
                print "Passport: Initialization. The attributes mapping isn't valid"
                return False
        if (configurationAttributes.containsKey("extension_module")):
            extensionModuleName = configurationAttributes.get("extension_module").getValue2()
            try:
                self.extensionModule = __import__(extensionModuleName)
                extensionModuleInitResult = self.extensionModule.init(configurationAttributes)
                if (not extensionModuleInitResult):
                    return False
            except ImportError, ex:
                print "Passport: Initialization. Failed to load generic_extension_module:", extensionModuleName
                print "Passport: Initialization. Unexpected error:", ex
                return False
Example #11
0
 def generateInum(self, orgInum, prefix):
     if StringHelper.isNotEmptyString(orgInum) and StringHelper.isNotEmptyString(prefix):
         return (
             orgInum + Configuration.inumDelimiter + prefix + Configuration.inumDelimiter + INumGenerator.generate()
         )
     else:
         return ""
    def getCurrentSamlConfiguration(self, currentSamlConfiguration, configurationAttributes, requestParameters):
        saml_client_configuration = self.getClientConfiguration(configurationAttributes, requestParameters)
        if (saml_client_configuration == None):
            return currentSamlConfiguration
        
        saml_client_configuration_value = json.loads(saml_client_configuration.getValue())

        client_saml_certificate = None      
        client_saml_certificate_file = saml_client_configuration_value["saml_certificate_file"]
        if (StringHelper.isNotEmpty(client_saml_certificate_file)):
            client_saml_certificate = self.loadCeritificate(client_saml_certificate_file)
            if (StringHelper.isEmpty(client_saml_certificate)):
                print "Saml. BuildClientSamlConfiguration. File with x509 certificate should be not empty. Using default configuration"
                return currentSamlConfiguration

        clientSamlConfiguration = currentSamlConfiguration.clone()
        
        if (client_saml_certificate != None):
            clientSamlConfiguration.loadCertificateFromString(client_saml_certificate)

        client_saml_issuer = saml_client_configuration_value["saml_issuer"]
        clientSamlConfiguration.setIssuer(client_saml_issuer)
        
        saml_use_authn_context = saml_client_configuration_value["saml_use_authn_context"]
        client_use_saml_use_authn_context = StringHelper.toBoolean(saml_use_authn_context, True)
        clientSamlConfiguration.setUseRequestedAuthnContext(client_use_saml_use_authn_context)

        return clientSamlConfiguration
    def sendPushNotification(self, user, oxpush2_request):
        if not self.enabledPushNotifications:
            return

        user_name = user.getUserId()
        print "oxPush2. Send push notification. Loading user '%s' devices" % user_name

        send_notification = False
        send_notification_result = True

        userService = UserService.instance()
        deviceRegistrationService = DeviceRegistrationService.instance()

        user_inum = userService.getUserInum(user_name)

        u2f_devices_list = deviceRegistrationService.findUserDeviceRegistrations(user_inum, self.application_id, "oxId", "oxDeviceData")
        if u2f_devices_list.size() > 0:
            for u2f_device in u2f_devices_list:
                device_data = u2f_device.getDeviceData()

                # Device data which oxPush2 gets during enrollment
                if device_data == None:
                    continue

                platform = device_data.getPlatform()
                push_token = device_data.getPushToken()
                debug = False

                if StringHelper.equalsIgnoreCase(platform, "ios") and StringHelper.isNotEmpty(push_token):
                    # Sending notification to iOS user's device
                    if (self.pushAppleService == None):
                        print "oxPush2. Send push notification. Apple push notification service is not enabled"
                    else:
                        send_notification = True
                        
                        title = "oxPush2"
                        message = "oxPush2 login request to: %s" % self.application_id

                        additional_fields = HashMap()
                        additional_fields.put("request", oxpush2_request)

                        send_notification_result = self.pushAppleService.sendPush(title, message, additional_fields, push_token)
                        if debug:
                            print "oxPush2. Send push notification. token: '%s', send_notification_result: '%s'" % (push_token, send_notification_result)

                if StringHelper.equalsIgnoreCase(platform, "android") and StringHelper.isNotEmpty(push_token):
                    # Sending notification to Android user's device
                    if (self.pushAndroidService == None):
                        print "oxPush2. Send push notification. Android push notification service is not enabled"
                    else:
                        send_notification = True
                        send_notification_result= self.pushAndroidService.sendPush("oxPush2", oxpush2_request, push_token)
                        if debug:
                            print "oxPush2. Send push notification. token: '%s', send_notification_result: '%s'" % (push_token, send_notification_result)


        print "oxPush2. Send push notification. send_notification: '%s', send_notification_result: '%s'" % (send_notification, send_notification_result)
    def prepareAttributesMapping(self, saml_idp_attributes_mapping):
        saml_idp_attributes_mapping_json = json.loads(saml_idp_attributes_mapping)
        
        if len(saml_idp_attributes_mapping_json) == 0:
            print "Saml. PrepareAttributesMapping. There is no attributes mapping specified in saml_idp_attributes_mapping property"
            return None

        attributeMapping = IdentityHashMap()
        for local_attribute_name in saml_idp_attributes_mapping_json:
            localAttribute = StringHelper.toLowerCase(local_attribute_name)
            for idp_attribute_name in saml_idp_attributes_mapping_json[local_attribute_name]:
                idpAttribute = StringHelper.toLowerCase(idp_attribute_name)
                attributeMapping.put(idpAttribute, localAttribute)
        
        return attributeMapping
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        if (step == 1):
            print "Basic (with password update). 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

            return True
        elif (step == 2):
            print "Basic (with password update). Authenticate for step 2"

            userService = UserService.instance()

            update_button = requestParameters.get("loginForm:updateButton")
            if ArrayHelper.isEmpty(update_button):
                return True

            new_password_array = requestParameters.get("new_password")
            if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty(new_password_array[0]):
                print "Basic (with password update). Authenticate for step 2. New password is empty"
                return False

            new_password = new_password_array[0]

            print "Basic (with password update). Authenticate for step 2. Attemprin to set new user '" + user_name + "' password"

            find_user_by_uid = userService.getUser(user_name)
            if (find_user_by_uid == None):
                print "Basic (with password update). Authenticate for step 2. Failed to find user"
                return False
            
            find_user_by_uid.setAttribute("userPassword", new_password)
            userService.updateUser(find_user_by_uid)
            print "Basic (with password update). Authenticate for step 2. Password updated successfully"

            return True
        else:
            return False
    def validateInweboToken(self, iw_api_uri, iw_service_id, user_name, iw_token):
        httpService = HttpService.instance()
        xmlService = XmlService.instance();

        if StringHelper.isEmpty(iw_token):
            print "InWebo. Token verification. iw_token is empty"
            return False

        request_uri = iw_api_uri + "?action=authenticate" + "&serviceId=" + httpService.encodeUrl(iw_service_id) + "&userId=" + httpService.encodeUrl(user_name) + "&token=" + httpService.encodeUrl(iw_token)
        print "InWebo. Token verification. Attempting to send authentication request:", request_uri
        # Execute request
        http_response = httpService.executeGet(self.client, request_uri)
            
        # Validate response code
        response_validation = httpService.isResponseStastusCodeOk(http_response)
        if response_validation == False:
            print "InWebo. Token verification. Get unsuccessful response code"
            return False

        authentication_response_bytes = httpService.getResponseContent(http_response)
        print "InWebo. Token verification. Get response:", httpService.convertEntityToString(authentication_response_bytes)

        # Validate authentication response
        response_validation = httpService.isContentTypeXml(http_response)
        if response_validation == False:
            print "InWebo. Token verification. Get invalid response"
            return False
        
        # Parse XML response
        try:
            xmlDocument = xmlService.getXmlDocument(authentication_response_bytes)
        except Exception, err:
            print "InWebo. Token verification. Failed to parse XML response:", err
            return False
    def getMappedUser(self, configurationAttributes, requestParameters, saml_response_attributes):
        # 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. Get mapped user. Using next attributes mapping '%s'" % currentAttributesMapping

        newUser = User()

        # Set custom object classes
        if self.userObjectClasses != None:
            print "Saml. Get mapped user. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList(self.userObjectClasses)
            newUser.setCustomObjectClasses(self.userObjectClasses)

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

            if self.debugEnrollment:
                print "Saml. Get mapped user. Trying to map '%s' into '%s'" % (idpAttribute, localAttribute)

            localAttributeValue = saml_response_normalized_attributes.get(idpAttribute)
            if (localAttributeValue != None):
                if self.debugEnrollment:
                    print "Saml. Get mapped user. Setting attribute '%s' value '%s'" % (localAttribute, localAttributeValue)

                newUser.setAttribute(localAttribute, localAttributeValue)

        return newUser
    def init(self, configurationAttributes):
        print "UAF. Initialization"

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

        self.uaf_server_uri = configurationAttributes.get("uaf_server_uri").getValue2()

        self.uaf_policy_name = "default"
        if configurationAttributes.containsKey("uaf_policy_name"):
            self.uaf_policy_name = configurationAttributes.get("uaf_policy_name").getValue2()

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

        self.registration_uri = None
        if configurationAttributes.containsKey("registration_uri"):
            self.registration_uri = configurationAttributes.get("registration_uri").getValue2()

        self.customQrOptions = {}
        if configurationAttributes.containsKey("qr_options"):
            self.customQrOptions = configurationAttributes.get("qr_options").getValue2()

        print "UAF. Initializing HTTP client"
        httpService = HttpService.instance()
        self.http_client = httpService.getHttpsClient()
        http_client_params = self.http_client.getParams()
        http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)

        print "UAF. Initialized successfully. uaf_server_uri: '%s', uaf_policy_name: '%s', send_push_notifaction: '%s', registration_uri: '%s', qr_options: '%s'" % (self.uaf_server_uri, self.uaf_policy_name, self.send_push_notifaction, self.registration_uri, self.customQrOptions)
        
        print "UAF. Initialized successfully"
        return True
    def updateClient(self, registerRequest, client, configurationAttributes):
        print "Client registration. UpdateClient method"

        redirectUris = client.getRedirectUris()
        print "Client registration. Redirect Uris:", redirectUris

        addAddressScope = False
        for redirectUri in redirectUris:
            if (StringHelper.equalsIgnoreCase(redirectUri, "https://client.example.com/example1")):
                addAddressScope = True
                break
        
        print "Client registration. Is add address scope:", addAddressScope

        if (addAddressScope):
            currentScopes = client.getScopes()
            print "Client registration. Current scopes:", currentScopes
            
            addressScope = self.scopeService.getScopeByDisplayName("address")
            newScopes = ArrayHelper.addItemToStringArray(currentScopes, addressScope.getDn())
    
            print "Client registration. Result scopes:", newScopes
            client.setScopes(newScopes)

        return True
    def checkStatus(self, mode, request_id, timeout):
        try:
            curTime = java.lang.System.currentTimeMillis()
            endTime = curTime + timeout * 1000
            while (endTime >= curTime):
                response_status = None
                if (StringHelper.equals("pair", mode)):
                    response_status = self.oxPushClient.getPairingStatus(request_id)
                else:
                    response_status = self.oxPushClient.getAuthenticationStatus(request_id)

                if (not response_status.result):
                    print "oxPush. CheckStatus. Get false result from oxPushServer"
                    return None

                status = response_status.status

                if ("declined" == status):
                    print "oxPush. CheckStatus. The process has been cancelled"
                    return None

                if ("expired" == status):
                    print "oxPush. CheckStatus. The process has been expired"
                    return None

                if ("approved" == status):
                    print "oxPush. CheckStatus. The process was approved"
                    return response_status

                java.lang.Thread.sleep(2000)
                curTime = java.lang.System.currentTimeMillis()
        except java.lang.Exception, err:
            print "oxPush. CheckStatus. Could not check process status: ", err
            return None
    def validateSessionDeviceStatus(self, client_redirect_uri, session_device_status, user_name = None):
        userService = UserService.instance()
        deviceRegistrationService = DeviceRegistrationService.instance()

        u2f_device_id = session_device_status['device_id']

        u2f_device = None
        if session_device_status['enroll'] and session_device_status['one_step']:
            u2f_device = deviceRegistrationService.findOneStepUserDeviceRegistration(u2f_device_id)
            if u2f_device == None:
                print "Super-Gluu. Validate session device status. There is no one step u2f_device '%s'" % u2f_device_id
                return False
        else:
            # Validate if user has specified device_id enrollment
            user_inum = userService.getUserInum(user_name)

            if session_device_status['one_step']:
                user_inum = session_device_status['user_inum']
    
            u2f_device = deviceRegistrationService.findUserDeviceRegistration(user_inum, u2f_device_id)
            if u2f_device == None:
                print "Super-Gluu. Validate session device status. There is no u2f_device '%s' associated with user '%s'" % (u2f_device_id, user_inum)
                return False

        if not StringHelper.equalsIgnoreCase(client_redirect_uri, u2f_device.application):
            print "Super-Gluu. Validate session device status. u2f_device '%s' associated with other application '%s'" % (u2f_device_id, u2f_device.application)
            return False
        
        return True
    def getMappedAllAttributesUser(self, saml_response_attributes):
        user = User()

        # Set custom object classes
        if self.userObjectClasses != None:
            print "Saml. Get mapped all attributes user. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList(self.userObjectClasses)
            user.setCustomObjectClasses(self.userObjectClasses)

        # Prepare map to do quick mapping 
        attributeService = AttributeService.instance()
        ldapAttributes = attributeService.getAllAttributes()
        samlUriToAttributesMap = HashMap()
        for ldapAttribute in ldapAttributes:
            saml2Uri = ldapAttribute.getSaml2Uri()
            if (saml2Uri == None):
                saml2Uri = attributeService.getDefaultSaml2Uri(ldapAttribute.getName())
            samlUriToAttributesMap.put(saml2Uri, ldapAttribute.getName())

        customAttributes = ArrayList()
        for key in saml_response_attributes.keySet():
            ldapAttributeName = samlUriToAttributesMap.get(key)
            if ldapAttributeName == None:
                print "Saml. Get mapped all attributes user. Skipping saml attribute: '%s'" %  key
                continue

            if StringHelper.equalsIgnoreCase(ldapAttributeName, "uid"):
                continue

            attribute = CustomAttribute(ldapAttributeName)
            attribute.setValues(saml_response_attributes.get(key))
            customAttributes.add(attribute)
        
        user.setCustomAttributes(customAttributes)

        return user
Example #23
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()

        user_name = credentials.getUsername()
        if (step == 1):
            print "Tiqr 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

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

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

            expected_user = credentials.getUser();
            if (expected_user == None):
                print "Tiqr authenticate for step 2. expected user is empty"
                return False

            expected_user_name = expected_user.getUserId();

            session = FacesContext.getCurrentInstance().getExternalContext().getSession(False)
            if (session == None):
                print "Tiqr authenticate for step 2. Session is not exist"
                return False

            authenticated_username = session.getValue("tiqr_user_uid")
            session.removeValue("tiqr_user_uid")

            print "Tiqr authenticate for step 2. authenticated_username: "******", expected user_name: " + expected_user_name

            if StringHelper.equals(expected_user_name, authenticated_username):
                return True

            return False
        else:
            return False
    def prepareUserObjectClasses(self, configurationAttributes):
        user_object_classes = configurationAttributes.get("user_object_classes").getValue2()

        user_object_classes_list_array = StringHelper.split(user_object_classes, ",")
        if (ArrayHelper.isEmpty(user_object_classes_list_array)):
            return None
        
        return user_object_classes_list_array
    def prepareUserEnforceUniquenessAttributes(self, configurationAttributes):
        enforce_uniqueness_attr_list = configurationAttributes.get("enforce_uniqueness_attr_list").getValue2()

        enforce_uniqueness_attr_list_array = StringHelper.split(enforce_uniqueness_attr_list, ",")
        if (ArrayHelper.isEmpty(enforce_uniqueness_attr_list_array)):
            return None
        
        return enforce_uniqueness_attr_list_array
    def init(self, configurationAttributes):
        print "User registration. Initialization"

        self.enable_user = StringHelper.toBoolean(configurationAttributes.get("enable_user").getValue2(), False)

        print "User registration. Initialized successfully"

        return True   
    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 prepareForStep(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()

        if (step == 1):
            context.set("display_register_action", True)
            return True
        elif (step == 2):
            print "oxPush2. Prepare for step 2"

            credentials = Identity.instance().getCredentials()
            user = credentials.getUser()
            if (user == None):
                print "oxPush2. Prepare for step 2. Failed to determine user name"
                return False

            session_attributes = context.get("sessionAttributes")
            if session_attributes.containsKey("oxpush2_request"):
                print "oxPush2. Prepare for step 2. Request was generated already"
                return True
            
            session_state = SessionStateService.instance().getSessionStateFromCookie()
            if StringHelper.isEmpty(session_state):
                print "oxPush2. Prepare for step 2. Failed to determine session_state"
                return False

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

            print "oxPush2. Prepare for step 2. auth_method: '%s'" % auth_method
            
            issuer = ConfigurationFactory.instance().getConfiguration().getIssuer()
            oxpush2_request = json.dumps({'username': user.getUserId(),
                               'app': self.u2f_application_id,
                               'issuer': issuer,
                               'method': auth_method,
                               'state': session_state}, separators=(',',':'))
            print "oxPush2. Prepare for step 2. Prepared oxpush2_request:", oxpush2_request

            context.set("oxpush2_request", oxpush2_request)

            return True
        else:
            return False
    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   
Example #30
0
    def authorize(self, authorizationContext):

        print "authorizing..."

        if StringHelper.equalsIgnoreCase(authorizationContext.getUserClaim("locality"), "Austin"):
            print "authorized"
            return True

        return False
Example #31
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)
        userService = CdiUtil.bean(UserService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()
        if step == 1:
            print "Basic (with password update). Authenticate for step 1"
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

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

            if not logged_in:
                return False

            find_user_by_uid = authenticationService.getAuthenticatedUser()
            user_expDate = find_user_by_uid.getAttribute(
                "oxPasswordExpirationDate", False)

            if user_expDate == None:
                print "Basic (with password update). Authenticate for step 1. User has no oxPasswordExpirationDate date"
                return False

            dt = StaticUtils.decodeGeneralizedTime(user_expDate)

            # Get Current Date
            calendar = GregorianCalendar(TimeZone.getTimeZone("UTC"))
            now = calendar.getTime()
            if now.compareTo(dt) > 0:
                # Add 90 Days to current date
                calendar.setTime(now)
                calendar.add(calendar.DATE, 1)
                dt_plus_90 = calendar.getTime()
                expDate = StaticUtils.encodeGeneralizedTime(dt_plus_90)
                identity.setWorkingParameter("expDate", expDate)

            return True
        elif step == 2:
            print "Basic (with password update). Authenticate for step 2"
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "Basic (with password update). Authenticate for step 2. Failed to determine user name"
                return False

            user_name = user.getUserId()
            find_user_by_uid = userService.getUser(user_name)
            newExpDate = identity.getWorkingParameter("expDate")
            if find_user_by_uid == None:
                print "Basic (with password update). Authenticate for step 2. Failed to find user"
                return False
            print "Basic (with password update). Authenticate for step 2"
            update_button = requestParameters.get("loginForm:updateButton")

            if ArrayHelper.isEmpty(update_button):
                return True

            find_user_by_uid.setAttribute("oxPasswordExpirationDate",
                                          newExpDate)
            new_password_array = requestParameters.get("loginForm:password")
            if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty(
                    new_password_array[0]):
                print "Basic (with password update). Authenticate for step 2. New password is empty"
                return False

            new_password = new_password_array[0]
            find_user_by_uid.setAttribute("userPassword", new_password)
            print "Basic (with password update). Authenticate for step 2. Attempting to set new user '%s' password" % user_name

            userService.updateUser(find_user_by_uid)
            print "Basic (with password update). Authenticate for step 2. Password updated successfully"

            return True
        else:
            return False
Example #32
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = Component.getInstance(UserService)

        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 = Component.getInstance(UserService)
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            # Find user by uid
            userService = Component.getInstance(UserService)
            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", 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

            sessionAttributes = context.get("sessionAttributes")
            if (sessionAttributes == None
                ) or not sessionAttributes.containsKey("oxpush_user_uid"):
                print "oxPush. Authenticate for step 2. oxpush_user_uid is empty"

                if (not sessionAttributes.containsKey("oxpush_pairing_uid")):
                    print "oxPush. Authenticate for step 2. oxpush_pairing_uid is empty"
                    return False

                oxpush_pairing_uid = sessionAttributes.get(
                    "oxpush_pairing_uid")

                # 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", 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

            sessionAttributes = context.get("oxpush_user_uid")
            if (sessionAttributes == None
                ) or not sessionAttributes.containsKey("oxpush_user_uid"):
                print "oxPush. Authenticate for step 3. oxpush_user_uid is empty"
                return False

            oxpush_user_uid = sessionAttributes.get("oxpush_user_uid")
            passed_step1 = StringHelper.isNotEmptyString(oxpush_user_uid)
            if (not passed_step1):
                return False

            # 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):
        authenticationService = CdiUtil.bean(AuthenticationService)

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

        user_name = credentials.getUsername()

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

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

            if (not logged_in):
                return False

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

            token_response = ServerUtil.getFirstValue(requestParameters,
                                                      "tokenResponse")
            if token_response == None:
                print "U2F. Authenticate for step 2. tokenResponse is empty"
                return False

            auth_method = ServerUtil.getFirstValue(requestParameters,
                                                   "authMethod")
            if auth_method == None:
                print "U2F. Authenticate for step 2. authMethod is empty"
                return False

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

            if (auth_method == 'authenticate'):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to finish authentication workflow"
                authenticationRequestService = FidoU2fClientFactory.instance(
                ).createAuthenticationRequestService(
                    self.metaDataConfiguration)
                authenticationStatus = authenticationRequestService.finishAuthentication(
                    user.getUserId(), token_response)

                if (authenticationStatus.getStatus() !=
                        Constants.RESULT_SUCCESS):
                    print "U2F. Authenticate for step 2. Get invalid authentication status from FIDO U2F server"
                    return False

                return True
            elif (auth_method == 'enroll'):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to finish registration workflow"
                registrationRequestService = FidoU2fClientFactory.instance(
                ).createRegistrationRequestService(self.metaDataConfiguration)
                registrationStatus = registrationRequestService.finishRegistration(
                    user.getUserId(), token_response)

                if (registrationStatus.getStatus() !=
                        Constants.RESULT_SUCCESS):
                    print "U2F. Authenticate for step 2. Get invalid registration status from FIDO U2F server"
                    return False

                return True
            else:
                print "U2F. Prepare for step 2. Authenticatiod method is invalid"
                return False

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

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

        self.setRequestScopedParameters(identity)

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

            otp_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second OTP registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    otp_auth_method = "enroll"

            if otp_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(
                    authenticated_user.getUserId())
                if len(user_enrollments) == 0:
                    otp_auth_method = "enroll"
                    print "OTP. Authenticate for step 1. There is no OTP enrollment for user '%s'. Changing otp_auth_method to '%s'" % (
                        authenticated_user.getUserId(), otp_auth_method)

            if otp_auth_method == "enroll":
                print "OTP. Authenticate for step 1. Setting count steps: '%s'" % 3
                identity.setWorkingParameter("otp_count_login_steps", 3)

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

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

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

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

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

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

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

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

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

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

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

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

            return otp_auth_result
        else:
            return False
Example #35
0
    def init(self, configurationAttributes):
        print "Asimba. Initialization"

        asimba_saml_certificate_file = configurationAttributes.get(
            "asimba_saml_certificate_file").getValue2()
        saml_idp_sso_target_url = configurationAttributes.get(
            "saml_idp_sso_target_url").getValue2()
        asimba_entity_id = configurationAttributes.get(
            "asimba_entity_id").getValue2()
        saml_use_authn_context = StringHelper.toBoolean(
            configurationAttributes.get("saml_use_authn_context").getValue2(),
            True)
        if (saml_use_authn_context):
            saml_name_identifier_format = configurationAttributes.get(
                "saml_name_identifier_format").getValue2()
        else:
            saml_name_identifier_format = None

        asimba_saml_certificate = self.loadCeritificate(
            asimba_saml_certificate_file)
        if (StringHelper.isEmpty(asimba_saml_certificate)):
            print "Asimba. Initialization. File with x509 certificate should be not empty"
            return False

        samlConfiguration = SamlConfiguration()

        # Set the issuer of the authentication request. This would usually be the URL of the issuing web application
        samlConfiguration.setIssuer(asimba_entity_id)

        # Tells the IdP to return a persistent identifier for the user
        samlConfiguration.setNameIdentifierFormat(saml_name_identifier_format)

        # The URL at the Identity Provider where to the authentication request should be sent
        samlConfiguration.setIdpSsoTargetUrl(saml_idp_sso_target_url)

        # Enablediable RequestedAuthnContext
        samlConfiguration.setUseRequestedAuthnContext(saml_use_authn_context)

        # Load x509 certificate
        samlConfiguration.loadCertificateFromString(asimba_saml_certificate)

        self.samlConfiguration = samlConfiguration

        self.generateNameId = False
        if configurationAttributes.containsKey("saml_generate_name_id"):
            self.generateNameId = StringHelper.toBoolean(
                configurationAttributes.get(
                    "saml_generate_name_id").getValue2(), False)
        print "Asimba. Initialization. The property saml_generate_name_id is %s" % self.generateNameId

        self.updateUser = False
        if configurationAttributes.containsKey("saml_update_user"):
            self.updateUser = StringHelper.toBoolean(
                configurationAttributes.get("saml_update_user").getValue2(),
                False)

        print "Asimba. Initialization. The property saml_update_user is %s" % self.updateUser

        self.userObjectClasses = None
        if configurationAttributes.containsKey("user_object_classes"):
            self.userObjectClasses = self.prepareUserObjectClasses(
                configurationAttributes)

        self.userEnforceAttributesUniqueness = None
        if configurationAttributes.containsKey("enforce_uniqueness_attr_list"):
            self.userEnforceAttributesUniqueness = self.prepareUserEnforceUniquenessAttributes(
                configurationAttributes)

        self.attributesMapping = None
        if configurationAttributes.containsKey("saml_idp_attributes_mapping"):
            saml_idp_attributes_mapping = configurationAttributes.get(
                "saml_idp_attributes_mapping").getValue2()
            if (StringHelper.isEmpty(saml_idp_attributes_mapping)):
                print "Asimba. Initialization. The property saml_idp_attributes_mapping is empty"
                return False

            self.attributesMapping = self.prepareAttributesMapping(
                saml_idp_attributes_mapping)
            if (self.attributesMapping == None):
                print "Asimba. Initialization. The attributes mapping isn't valid"
                return False

        self.samlExtensionModule = None
        if (configurationAttributes.containsKey("saml_extension_module")):
            saml_extension_module_name = configurationAttributes.get(
                "saml_extension_module").getValue2()
            try:
                self.samlExtensionModule = __import__(
                    saml_extension_module_name)
                saml_extension_module_init_result = self.samlExtensionModule.init(
                    configurationAttributes)
                if (not saml_extension_module_init_result):
                    return False
            except ImportError, ex:
                print "Asimba. Initialization. Failed to load saml_extension_module: '%s'" % saml_extension_module_name
                print "Asimba. Initialization. Unexpected error:", ex
                return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        user_name = credentials.getUsername()

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

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

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

                return recaptcha_result

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

            # Validate if user selected certificate
            cert_x509 = self.getSessionAttribute("cert_x509")
            if cert_x509 == None:
                print "Cert. Authenticate for step 2. User not selected any certs"
                identity.setWorkingParameter("cert_selected", False)

                # Return True to inform user how to reset workflow
                return True
            else:
                identity.setWorkingParameter("cert_selected", True)
                x509Certificate = self.certFromString(cert_x509)

            subjectX500Principal = x509Certificate.getSubjectX500Principal()
            print "Cert. Authenticate for step 2. User selected certificate with DN '%s'" % subjectX500Principal

            # Validate certificates which user selected
            valid = self.validateCertificate(x509Certificate)
            if not valid:
                print "Cert. Authenticate for step 2. Certificate DN '%s' is not valid" % subjectX500Principal
                identity.setWorkingParameter("cert_valid", False)

                # Return True to inform user how to reset workflow
                return True

            identity.setWorkingParameter("cert_valid", True)

            # Calculate certificate fingerprint
            x509CertificateFingerprint = self.calculateCertificateFingerprint(
                x509Certificate)
            identity.setWorkingParameter("cert_x509_fingerprint",
                                         x509CertificateFingerprint)
            print "Cert. Authenticate for step 2. Fingerprint is '%s' of certificate with DN '%s'" % (
                x509CertificateFingerprint, subjectX500Principal)

            # Attempt to find user by certificate fingerprint
            cert_user_external_uid = "cert:%s" % x509CertificateFingerprint
            print "Cert. Authenticate for step 2. Attempting to find user by oxExternalUid attribute value %s" % cert_user_external_uid

            find_user_by_external_uid = userService.getUserByAttribute(
                "oxExternalUid", cert_user_external_uid)
            if find_user_by_external_uid == None:
                print "Cert. Authenticate for step 2. Failed to find user"

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

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

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

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

            user_password = credentials.getPassword()

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

            if (not logged_in):
                return False

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

                return True

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

        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        session_attributes = self.identity.getSessionId().getSessionAttributes(
        )
        form_passcode = ServerUtil.getFirstValue(requestParameters, "passcode")
        form_name = ServerUtil.getFirstValue(requestParameters,
                                             "TwilioSmsloginForm")

        print "TwilioSMS. form_response_passcode: %s" % str(form_passcode)

        if step == 1:
            print "TwilioSMS. Step 1 Password Authentication"
            credentials = self.identity.getCredentials()

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

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

            if not logged_in:
                return False

            # Get the Person's number and generate a code
            foundUser = None
            try:
                foundUser = authenticationService.getAuthenticatedUser()
            except:
                print 'TwilioSMS, Error retrieving user %s from LDAP' % (
                    user_name)
                return False

            try:
                isVerified = foundUser.getAttribute("phoneNumberVerified")
                if isVerified:
                    self.mobile_number = foundUser.getAttribute(
                        "employeeNumber")
                if self.mobile_number == None:
                    self.mobile_number = foundUser.getAttribute("mobile")
                if self.mobile_number == None:
                    self.mobile_number = foundUser.getAttribute(
                        "telephoneNumber")
                if self.mobile_number == None:
                    print "TwilioSMS, Error finding mobile number for user '%'" % user_name

            except:
                facesMessages.add(FacesMessage.SEVERITY_ERROR,
                                  "Failed to determine mobile phone number")
                print 'TwilioSMS, Error finding mobile number for' % (
                    user_name)
                return False

            # Generate Random six digit code and store it in array
            code = random.randint(100000, 999999)

            # Get code and save it in LDAP temporarily with special session entry
            self.identity.setWorkingParameter("code", code)

            try:
                Twilio.init(self.ACCOUNT_SID, self.AUTH_TOKEN)
                message = Message.creator(PhoneNumber(self.mobile_number),
                                          PhoneNumber(self.FROM_NUMBER),
                                          str(code)).create()
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                print 'TwilioSMs, Message Sid: %s' % (message.getSid())
                print 'TwilioSMs, User phone: %s' % (self.mobile_number)
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                self.identity.setWorkingParameter("mobile_number",
                                                  self.mobile_number)
                self.identity.getSessionId().getSessionAttributes().put(
                    "mobile_number", self.mobile_number)
                self.identity.setWorkingParameter("mobile", self.mobile_number)
                self.identity.getSessionId().getSessionAttributes().put(
                    "mobile", self.mobile_number)
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                print "Number: %s" % (
                    self.identity.getWorkingParameter("mobile_number"))
                print "Mobile: %s" % (
                    self.identity.getWorkingParameter("mobile"))
                print "++++++++++++++++++++++++++++++++++++++++++++++"
                return True
            except Exception, ex:
                facesMessages.add(FacesMessage.SEVERITY_ERROR,
                                  "Failed to send message to mobile phone")
                print "TwilioSMS. Error sending message to Twilio"
                print "TwilioSMS. Unexpected error:", ex

            return False
    def isPassedStep1():
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()
        passed_step1 = StringHelper.isNotEmptyString(user_name)

        return passed_step1
    def init(self, configurationAttributes):
        print "Saml. Initialization"

        saml_certificate_file = configurationAttributes.get("saml_certificate_file").getValue2()
        saml_idp_sso_target_url = configurationAttributes.get("saml_idp_sso_target_url").getValue2()
        saml_issuer = configurationAttributes.get("saml_issuer").getValue2()
        saml_use_authn_context = StringHelper.toBoolean(configurationAttributes.get("saml_use_authn_context").getValue2(), True)
        if (saml_use_authn_context):
            saml_name_identifier_format = configurationAttributes.get("saml_name_identifier_format").getValue2()
        else:
            saml_name_identifier_format = None

        saml_certificate = self.loadCeritificate(saml_certificate_file)
        if (StringHelper.isEmpty(saml_certificate)):
            print "Saml. Initialization. File with x509 certificate should be not empty"
            return False

        samlConfiguration = SamlConfiguration()

        # Set the issuer of the authentication request. This would usually be the URL of the issuing web application
        samlConfiguration.setIssuer(saml_issuer)

        # Tells the IdP to return a persistent identifier for the user
        samlConfiguration.setNameIdentifierFormat(saml_name_identifier_format)
  
        # The URL at the Identity Provider where to the authentication request should be sent
        samlConfiguration.setIdpSsoTargetUrl(saml_idp_sso_target_url)

        # Enablediable RequestedAuthnContext
        samlConfiguration.setUseRequestedAuthnContext(saml_use_authn_context)
        
        # Load x509 certificate
        samlConfiguration.loadCertificateFromString(saml_certificate)
        
        self.samlConfiguration = samlConfiguration

        self.attributesMapping = None
        if (configurationAttributes.containsKey("saml_idp_attributes_list") and
            configurationAttributes.containsKey("saml_local_attributes_list")):

            saml_idp_attributes_list = configurationAttributes.get("saml_idp_attributes_list").getValue2()
            if (StringHelper.isEmpty(saml_idp_attributes_list)):
                print "Saml. Initialization. The property saml_idp_attributes_list is empty"
                return False

            saml_local_attributes_list = configurationAttributes.get("saml_local_attributes_list").getValue2()
            if (StringHelper.isEmpty(saml_local_attributes_list)):
                print "Saml. Initialization. The property saml_local_attributes_list is empty"
                return False

            self.attributesMapping = self.prepareAttributesMapping(saml_idp_attributes_list, saml_local_attributes_list)
            if (self.attributesMapping == None):
                print "Saml. Initialization. The attributes mapping isn't valid"
                return False

        self.samlExtensionModule = None
        if (configurationAttributes.containsKey("saml_extension_module")):
            saml_extension_module_name = configurationAttributes.get("saml_extension_module").getValue2()
            try:
                self.samlExtensionModule = __import__(saml_extension_module_name)
                saml_extension_module_init_result = self.samlExtensionModule.init(configurationAttributes)
                if (not saml_extension_module_init_result):
                    return False
            except ImportError, ex:
                print "Saml. Initialization. Failed to load saml_extension_module:", saml_extension_module_name
                print "Saml. Initialization. Unexpected error:", ex
                return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()

        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):
            # Detect if user used basic authnetication method
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            if (StringHelper.isNotEmpty(user_name) and StringHelper.isNotEmpty(user_password)):
                use_basic_auth = True

        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", 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, True)
                    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
            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, True)
                    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"

            sessionAttributes = context.get("sessionAttributes")
            if (sessionAttributes == None) or not sessionAttributes.containsKey("saml_user_uid"):
                print "Saml. Authenticate for step 2. saml_user_uid is empty"
                return False

            saml_user_uid = sessionAttributes.get("saml_user_uid")
            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
Example #41
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        mapUserDeployment = False
        enrollUserDeployment = False
        if (configurationAttributes.containsKey("gplus_deployment_type")):
            deploymentType = StringHelper.toLowerCase(configurationAttributes.get("gplus_deployment_type").getValue2())
            
            if (StringHelper.equalsIgnoreCase(deploymentType, "map")):
                mapUserDeployment = True
            if (StringHelper.equalsIgnoreCase(deploymentType, "enroll")):
                enrollUserDeployment = True

        if (step == 1):
            print "Google+ Authenticate for step 1"
 
            gplusAuthCodeArray = requestParameters.get("gplus_auth_code")
            gplusAuthCode = gplusAuthCodeArray[0]

            # Check if user uses basic method to log in
            useBasicAuth = False
            if (StringHelper.isEmptyString(gplusAuthCode)):
                useBasicAuth = True

            # Use basic method to log in
            if (useBasicAuth):
                print "Google+ Authenticate for step 1. Basic authentication"
        
                identity.setWorkingParameter("gplus_count_login_steps", 1)
        
                credentials = identity.getCredentials()

                userName = credentials.getUsername()
                userPassword = credentials.getPassword()
        
                loggedIn = False
                if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                    userService = CdiUtil.bean(UserService)
                    loggedIn = authenticationService.authenticate(userName, userPassword)
        
                if (not loggedIn):
                    return False
        
                return True

            # Use Google+ method to log in
            print "Google+ Authenticate for step 1. gplusAuthCode:", gplusAuthCode

            currentClientSecrets = self.getCurrentClientSecrets(self.clientSecrets, configurationAttributes, requestParameters)
            if (currentClientSecrets == None):
                print "Google+ Authenticate for step 1. Client secrets configuration is invalid"
                return False
            
            print "Google+ Authenticate for step 1. Attempting to gets tokens"
            tokenResponse = self.getTokensByCode(self.clientSecrets, configurationAttributes, gplusAuthCode)
            if ((tokenResponse == None) or (tokenResponse.getIdToken() == None) or (tokenResponse.getAccessToken() == None)):
                print "Google+ Authenticate for step 1. Failed to get tokens"
                return False
            else:
                print "Google+ Authenticate for step 1. Successfully gets tokens"

            jwt = Jwt.parse(tokenResponse.getIdToken())
            # TODO: Validate ID Token Signature  

            gplusUserUid = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER)
            print "Google+ Authenticate for step 1. Found Google user ID in the ID token: '%s'" % gplusUserUid
            
            if (mapUserDeployment):
                # Use mapping to local IDP user
                print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: 'gplus:%s'" % gplusUserUid

                # Check if there is user with specified gplusUserUid
                foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid)

                if (foundUser == None):
                    print "Google+ Authenticate for step 1. Failed to find user"
                    print "Google+ Authenticate for step 1. Setting count steps to 2"
                    identity.setWorkingParameter("gplus_count_login_steps", 2)
                    identity.setWorkingParameter("gplus_user_uid", gplusUserUid)
                    return True

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName
                
                userAuthenticated = authenticationService.authenticate(foundUserName)
                if (userAuthenticated == False):
                    print "Google+ Authenticate for step 1. Failed to authenticate user"
                    return False
            
                print "Google+ Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("gplus_count_login_steps", 1)

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
            elif (enrollUserDeployment):
                # Use auto enrollment to local IDP
                print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: 'gplus:%s'" % gplusUserUid
 
                # Check if there is user with specified gplusUserUid
                foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid)
 
                if (foundUser == None):
                    # Auto user enrollemnt
                    print "Google+ Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP"

                    print "Google+ Authenticate for step 1. Attempting to gets user info"
                    userInfoResponse = self.getUserInfo(currentClientSecrets, configurationAttributes, tokenResponse.getAccessToken())
                    if ((userInfoResponse == None) or (userInfoResponse.getClaims().size() == 0)):
                        print "Google+ Authenticate for step 1. Failed to get user info"
                        return False
                    else:
                        print "Google+ Authenticate for step 1. Successfully gets user info"
                    
                    gplusResponseAttributes = userInfoResponse.getClaims()
 
                    # Convert Google+ user claims to lover case
                    gplusResponseNormalizedAttributes = HashMap()
                    for gplusResponseAttributeEntry in gplusResponseAttributes.entrySet():
                        gplusResponseNormalizedAttributes.put(
                            StringHelper.toLowerCase(gplusResponseAttributeEntry.getKey()), gplusResponseAttributeEntry.getValue())
 
                    currentAttributesMapping = self.getCurrentAttributesMapping(self.attributesMapping, configurationAttributes, requestParameters)
                    print "Google+ Authenticate for step 1. Using next attributes mapping '%s'" % currentAttributesMapping
 
                    newUser = User()
                    for attributesMappingEntry in currentAttributesMapping.entrySet():
                        remoteAttribute = attributesMappingEntry.getKey()
                        localAttribute = attributesMappingEntry.getValue()
 
                        localAttributeValue = gplusResponseNormalizedAttributes.get(remoteAttribute)
                        if (localAttribute != None):
                            newUser.setAttribute(localAttribute, localAttributeValue)
 
                    if (newUser.getAttribute("sn") == None):
                        newUser.setAttribute("sn", gplusUserUid)
 
                    if (newUser.getAttribute("cn") == None):
                        newUser.setAttribute("cn", gplusUserUid)

                    newUser.setAttribute("oxExternalUid", "gplus:" + gplusUserUid)
                    print "Google+ Authenticate for step 1. Attempting to add user '%s' with next attributes '%s'" % (gplusUserUid, newUser.getCustomAttributes())
 
                    foundUser = userService.addUser(newUser, True)
                    print "Google+ Authenticate for step 1. Added new user with UID: '%s'" % foundUser.getUserId()

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName

                userAuthenticated = authenticationService.authenticate(foundUserName)
                if (userAuthenticated == False):
                    print "Google+ Authenticate for step 1. Failed to authenticate user"
                    return False

                print "Google+ Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("gplus_count_login_steps", 1)

                print "Google+ Authenticate for step 1. Attempting to run extension postLogin"
                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
            else:
                # Check if there is user with specified gplusUserUid
                print "Google+ Authenticate for step 1. Attempting to find user by uid: '%s'" % gplusUserUid

                foundUser = userService.getUser(gplusUserUid)
                if (foundUser == None):
                    print "Google+ Authenticate for step 1. Failed to find user"
                    return False

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName

                userAuthenticated = authenticationService.authenticate(foundUserName)
                if (userAuthenticated == False):
                    print "Google+ Authenticate for step 1. Failed to authenticate user"
                    return False

                print "Google+ Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("gplus_count_login_steps", 1)

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
        elif (step == 2):
            print "Google+ Authenticate for step 2"
            
            sessionAttributes = identity.getSessionId().getSessionAttributes()
            if (sessionAttributes == None) or not sessionAttributes.containsKey("gplus_user_uid"):
                print "Google+ Authenticate for step 2. gplus_user_uid is empty"
                return False

            gplusUserUid = sessionAttributes.get("gplus_user_uid")
            passed_step1 = StringHelper.isNotEmptyString(gplusUserUid)
            if (not passed_step1):
                return False

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

            userName = credentials.getUsername()
            userPassword = credentials.getPassword()

            loggedIn = False
            if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                loggedIn = authenticationService.authenticate(userName, userPassword)

            if (not loggedIn):
                return False

            # Check if there is user which has gplusUserUid
            # Avoid mapping Google account to more than one IDP account
            foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid)

            if (foundUser == None):
                # Add gplusUserUid to user one id UIDs
                foundUser = userService.addUserAttribute(userName, "oxExternalUid", "gplus:" + gplusUserUid)
                if (foundUser == None):
                    print "Google+ Authenticate for step 2. Failed to update current user"
                    return False

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 2. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
            else:
                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 2. foundUserName: '******'" % foundUserName
    
                if StringHelper.equals(userName, foundUserName):
                    postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                    print "Google+ Authenticate for step 2. postLoginResult: '%s'" % postLoginResult
    
                    return postLoginResult
        
            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "Wikid. Authentication. Checking client"

        if (not self.wc.isConnected()):
            print "Wikid. Authentication. Wikid client state is invalid"
            return False

        context = Contexts.getEventContext()

        is_wikid_registration = False
        sessionAttributes = context.get("sessionAttributes")
        if (sessionAttributes !=
                None) and sessionAttributes.containsKey("wikid_registration"):
            is_wikid_registration = java.lang.Boolean.valueOf(
                sessionAttributes.get("wikid_registration"))

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

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

        if (step == 1):
            print "Wikid. 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

            print "Wikid. Authenticate for step 1. Attempting to find wikid_user: "******"Wikid. Authenticate for step 1. There is no associated devices for user: "******"Wikid. Authenticate for step 1. Setting count steps to 3"
                context.set("wikid_count_login_steps", 3)
                context.set("wikid_registration", True)
            else:
                context.set("wikid_count_login_steps", 2)

            return True
        elif (is_wikid_registration):
            print "Wikid. Authenticate for step wikid_register_device"

            userService = UserService.instance()

            wikid_regcode_array = requestParameters.get("regcode")
            if ArrayHelper.isEmpty(wikid_regcode_array):
                print "Wikid. Authenticate for step wikid_register_device. Regcode is empty"
                return False

            wikid_regcode = wikid_regcode_array[0]

            print "Wikid. Authenticate for step wikid_register_device. User: "******", regcode: " + wikid_regcode

            register_result = self.wc.registerUsername(user_name,
                                                       wikid_regcode,
                                                       wikid_server_code)

            is_valid = register_result == 0
            if is_valid:
                print "Wikid. Authenticate for step wikid_register_device. User: "******" token registered successfully"

                # Add wikid_regcode to user UIDs
                find_user_by_uid = userService.addUserAttribute(
                    user_name, "oxExternalUid", "wikid:" + wikid_regcode)
                if (find_user_by_uid == None):
                    print "Wikid. Authenticate for step wikid_register_device. Failed to update user: "******"wikid_registration", False)
            else:
                print "Wikid. Authenticate for step wikid_register_device. Failed to register user: "******" token:" + wikid_regcode + ". Registration result:", register_result

            return is_valid
        elif (not is_wikid_registration):
            print "Wikid. Authenticate for step wikid_check_passcode"

            wikid_passcode_array = requestParameters.get("passcode")
            if ArrayHelper.isEmpty(wikid_passcode_array):
                print "Wikid. Authenticate for step wikid_check_passcode. Passcode is empty"
                return False

            wikid_passcode = wikid_passcode_array[0]

            print "Wikid. Authenticate for step wikid_check_passcode. wikid_user: "******"Wikid. Authenticate for step wikid_check_passcode. wikid_user: "******" authenticated successfully"
            else:
                print "Wikid. Authenticate for step wikid_check_passcode. Failed to authenticate. wikid_user: " + user_name

            return is_valid
        else:
            return False
    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)
        if self.chain_certs == None:
            print "Cert. Initialization. Failed to load chain certificates from '%s'" % chain_cert_file_path
            return False

        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 containsAttributeString(self, dictionary, attribute):
     return ((attribute in dictionary) and StringHelper.isNotEmptyString(dictionary[attribute]))
    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
Example #46
0
 def setDefaultUid(self, user, saml_user_uid):
     if StringHelper.isEmpty(user.getUserId()):
         user.setUserId(saml_user_uid)
Example #47
0
    def authenticate(self, configurationAttributes, requestParameters, step):

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

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

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

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

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

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

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

                return self.attemptAuthentication(identity, user_profile, json)

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

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

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

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

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

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

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

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

                return self.attemptAuthentication(identity, user_profile, json)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False
Example #48
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = Component.getInstance(AuthenticationService)
        userService = Component.getInstance(UserService)

        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):
            # Detect if user used basic authnetication method
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            if (StringHelper.isNotEmpty(user_name)
                    and StringHelper.isNotEmpty(user_password)):
                use_basic_auth = True

        if ((step == 1) and saml_allow_basic_login and use_basic_auth):
            print "Asimba. 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 = Component.getInstance(UserService)
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            return True

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

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

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

            saml_response = saml_response_array[0]

            print "Asimba. Authenticate for step 1. saml_response: '%s'" % 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 "Asimba. Authenticate for step 1. saml_response isn't valid"

            saml_response_attributes = samlResponse.getAttributes()
            print "Asimba. Authenticate for step 1. attributes: '%s'" % saml_response_attributes

            if (saml_map_user):
                saml_user_uid = self.getSamlNameId(samlResponse)
                if saml_user_uid == None:
                    return False

                # Use mapping to local IDP user
                print "Asimba. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid

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

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

                found_user_name = find_user_by_uid.getUserId()
                print "Asimba. Authenticate for step 1. found_user_name: '%s'" % found_user_name

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

                print "Asimba. 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 "Asimba. Authenticate for step 1. post_login_result: '%s'" % post_login_result

                return post_login_result
            elif (saml_enroll_user):
                # Convert SAML response to user entry
                newUser = self.getMappedUser(configurationAttributes,
                                             requestParameters,
                                             saml_response_attributes)

                saml_user_uid = self.getNameId(samlResponse, newUser)
                if saml_user_uid == None:
                    return False

                self.setDefaultUid(newUser, saml_user_uid)
                newUser.setAttribute("oxExternalUid",
                                     "saml:%s" % saml_user_uid)

                # Use auto enrollment to local IDP
                print "Asimba. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid

                # Check if there is user with specified saml_user_uid
                find_user_by_uid = userService.getUserByAttribute(
                    "oxExternalUid", "saml:%s" % saml_user_uid)
                if find_user_by_uid == None:
                    # Auto user enrollment
                    print "Asimba. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP"

                    print "Asimba. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % (
                        saml_user_uid, newUser.getCustomAttributes())
                    user_unique = self.checkUserUniqueness(newUser)
                    if not user_unique:
                        print "Asimba. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getUserId(
                        )
                        facesMessages = FacesMessages.instance()
                        facesMessages.add(
                            StatusMessage.Severity.ERROR,
                            "Failed to enroll. User with same key attributes exist already"
                        )
                        FacesContext.getCurrentInstance().getExternalContext(
                        ).getFlash().setKeepMessages(True)
                        return False

                    find_user_by_uid = userService.addUser(newUser, True)
                    print "Asimba. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId(
                    )
                else:
                    if self.updateUser:
                        print "Asimba. Authenticate for step 1. Attempting to update user '%s' with next attributes: '%s'" % (
                            saml_user_uid, newUser.getCustomAttributes())
                        find_user_by_uid.setCustomAttributes(
                            newUser.getCustomAttributes())
                        userService.updateUser(find_user_by_uid)
                        print "Asimba. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid

                found_user_name = find_user_by_uid.getUserId()
                print "Asimba. Authenticate for step 1. found_user_name: '%s'" % found_user_name

                user_authenticated = authenticationService.authenticate(
                    found_user_name)
                if (user_authenticated == False):
                    print "Asimba. Authenticate for step 1. Failed to authenticate user: '******'" % found_user_name
                    return False

                print "Asimba. 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 "Asimba. Authenticate for step 1. post_login_result: '%s'" % post_login_result

                return post_login_result
            elif (saml_enroll_all_user_attr):
                # Convert SAML response to user entry
                newUser = self.getMappedAllAttributesUser(
                    saml_response_attributes)

                saml_user_uid = self.getNameId(samlResponse, newUser)
                if saml_user_uid == None:
                    return False

                self.setDefaultUid(newUser, saml_user_uid)
                newUser.setAttribute("oxExternalUid",
                                     "saml:%s" % saml_user_uid)

                print "Asimba. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:%s" % saml_user_uid

                # Check if there is user with specified saml_user_uid
                find_user_by_uid = userService.getUserByAttribute(
                    "oxExternalUid", "saml:%s" % saml_user_uid)
                if (find_user_by_uid == None):
                    # Auto user enrollment
                    print "Asimba. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP"

                    print "Asimba. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % (
                        saml_user_uid, newUser.getCustomAttributes())
                    user_unique = self.checkUserUniqueness(newUser)
                    if not user_unique:
                        print "Asimba. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getUserId(
                        )
                        facesMessages = FacesMessages.instance()
                        facesMessages.add(
                            StatusMessage.Severity.ERROR,
                            "Failed to enroll. User with same key attributes exist already"
                        )
                        FacesContext.getCurrentInstance().getExternalContext(
                        ).getFlash().setKeepMessages(True)
                        return False

                    find_user_by_uid = userService.addUser(newUser, True)
                    print "Asimba. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId(
                    )
                else:
                    if self.updateUser:
                        print "Asimba. Authenticate for step 1. Attempting to update user '%s' with next attributes: '%s'" % (
                            saml_user_uid, newUser.getCustomAttributes())
                        find_user_by_uid.setCustomAttributes(
                            newUser.getCustomAttributes())
                        userService.updateUser(find_user_by_uid)
                        print "Asimba. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid

                found_user_name = find_user_by_uid.getUserId()
                print "Asimba. Authenticate for step 1. found_user_name: '%s'" % found_user_name

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

                print "Asimba. 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 "Asimba. Authenticate for step 1. post_login_result: '%s'" % post_login_result

                return post_login_result
            else:
                if saml_user_uid == None:
                    return False

                # Check if the is user with specified saml_user_uid
                print "Asimba. Authenticate for step 1. Attempting to find user by uid: '%s'" % saml_user_uid

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

                found_user_name = find_user_by_uid.getUserId()
                print "Asimba. Authenticate for step 1. found_user_name: '%s'" % found_user_name

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

                print "Asimba. 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 "Asimba. Authenticate for step 1. post_login_result: '%s'" % post_login_result

                return post_login_result
        elif (step == 2):
            print "Asimba. Authenticate for step 2"

            sessionAttributes = context.get("sessionAttributes")
            if (sessionAttributes == None
                ) or not sessionAttributes.containsKey("saml_user_uid"):
                print "Asimba. Authenticate for step 2. saml_user_uid is empty"
                return False

            saml_user_uid = sessionAttributes.get("saml_user_uid")
            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:%s" % 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:%s" % saml_user_uid)
                if (find_user_by_uid == None):
                    print "Asimba. Authenticate for step 2. Failed to update current user"
                    return False

                post_login_result = self.samlExtensionPostLogin(
                    configurationAttributes, find_user_by_uid)
                print "Asimba. Authenticate for step 2. post_login_result: '%s'" % post_login_result

                return post_login_result
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "Asimba. Authenticate for step 2. found_user_name: '%s'" % found_user_name

                if StringHelper.equals(user_name, found_user_name):
                    post_login_result = self.samlExtensionPostLogin(
                        configurationAttributes, find_user_by_uid)
                    print "Asimba. Authenticate for step 2. post_login_result: '%s'" % post_login_result

                    return post_login_result

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

        identity = CdiUtil.bean(Identity)
        session_attributes = identity.getSessionState().getSessionAttributes()

        form_passcode = ServerUtil.getFirstValue(requestParameters, "passcode")
        form_name = ServerUtil.getFirstValue(requestParameters,
                                             "TwilioSmsloginForm")

        print "TwilioSMS. form_response_passcode: %s" % str(form_passcode)

        if step == 1:
            print "TwilioSMS. Step 1 Password Authentication"
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()

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

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

            if not logged_in:
                return False

            # Get the Person's number and generate a code
            foundUser = None
            try:
                foundUser = userService.getUserByAttribute("uid", user_name)
            except:
                print 'TwilioSMS, Error retrieving user %s from LDAP' % (
                    user_name)
                return False

            try:
                mobile_number = foundUser.getAttribute("phoneNumberVerified")
            except:
                print 'TwilioSMS, Error finding mobile number for' % (
                    user_name)
                return False

            # Generate Random six digit code and store it in array
            code = random.randint(100000, 999999)

            # Get code and save it in LDAP temporarily with special session entry
            identity.setWorkingParameter("code", code)

            client = TwilioRestClient(self.ACCOUNT_SID, self.AUTH_TOKEN)
            bodyParam = BasicNameValuePair("Body", str(code))
            toParam = BasicNameValuePair("To", mobile_number)
            fromParam = BasicNameValuePair("From", self.FROM_NUMBER)

            params = ArrayList()
            params.add(bodyParam)
            params.add(toParam)
            params.add(fromParam)

            try:
                messageFactory = client.getAccount().getMessageFactory()
                message = messageFactory.create(params)

                print 'TwilioSMs, Message Sid: %s' % (message.getSid())
                return True
            except Exception, ex:
                print "TwilioSMS. Error sending message to Twilio"
                print "TwilioSMS. Unexpected error:", ex

            return False
Example #50
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        duo_host = configurationAttributes.get("duo_host").getValue2()

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

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

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

            if (not logged_in):
                return False

            authenticationService = Component.getInstance(
                AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (self.use_duo_group):
                print "Duo. Authenticate for step 1. Checking if user belong to Duo group"
                is_member_duo_group = self.isUserMemberOfGroup(
                    user, self.audit_attribute, self.duo_group)
                if (is_member_duo_group):
                    print "Duo. Authenticate for step 1. User '" + user.getUserId(
                    ) + "' member of Duo group"
                    duo_count_login_steps = 2
                else:
                    self.processAuditGroup(user)
                    duo_count_login_steps = 1

                context = Contexts.getEventContext()
                context.set("duo_count_login_steps", duo_count_login_steps)

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

            sig_response_array = requestParameters.get("sig_response")
            if ArrayHelper.isEmpty(sig_response_array):
                print "Duo. Authenticate for step 2. sig_response is empty"
                return False

            duo_sig_response = sig_response_array[0]

            print "Duo. Authenticate for step 2. duo_sig_response: " + duo_sig_response

            authenticated_username = duo_web.verify_response(
                self.ikey, self.skey, self.akey, duo_sig_response)

            print "Duo. Authenticate for step 2. authenticated_username: "******", expected user_name: " + user_name

            if (not StringHelper.equals(user_name, authenticated_username)):
                return False

            authenticationService = Component.getInstance(
                AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            self.processAuditGroup(user)

            return True
        else:
            return False
Example #51
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = Component.getInstance(AuthenticationService)
        userService = Component.getInstance(UserService)
        httpService = Component.getInstance(HttpService)

        cas_host = configurationAttributes.get("cas_host").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)

        cas_extra_opts = None
        if (configurationAttributes.containsKey("cas_extra_opts")):
            cas_extra_opts = configurationAttributes.get(
                "cas_extra_opts").getValue2()

        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 (cas_extra_opts != None):
                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.getHttpsClient()
            http_service_response = httpService.executeGet(
                http_client, cas_service_request_uri)

            try:
                validation_content = httpService.convertEntityToString(
                    httpService.getResponseContent(
                        http_service_response.getHttpResponse()))
            finally:
                http_service_response.closeConnection()

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

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

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

            if ((cas2_auth_failure != None) or (cas2_user_uid == None)):
                print "CAS2. Authenticate for step 1. Ticket is invalid"
                return False

            if (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", 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"

            sessionAttributes = context.get("sessionAttributes")
            if (sessionAttributes == None
                ) or not sessionAttributes.containsKey("cas2_user_uid"):
                print "CAS2. Authenticate for step 2. cas2_user_uid is empty"
                return False

            cas2_user_uid = sessionAttributes.get("cas2_user_uid")
            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()
    	
        if (step == 1):
            printOut("Step 1 Password Authentication")
            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
            
            # Get Custom Properties
            ACCOUNT_SID = None
    		AUTH_TOKEN = None
    		FROM_NUMBER = None
            try:    
	            ACCOUNT_SID = configurationAttributes.get("twilio_sid").getValue2()
	    	except:
	    		printOut('Missing required configuration attribute "twilio_sid"')
	    	try:
	    		AUTH_TOKEN = configurationAttributes.get("twilio_token").getValue2()
	    	except:
	    		printOut('Missing required configuration attribute "twilio_token")
	    	try:
	    		FROM_NUMBER = configurationAttributes.get("from_number").getValue2()
	    	except:
	    		printOut('Missing required configuration attribute "from_number"')
	    	if None in (ACCOUNT_SID, AUTH_TOKEN, FROM_NUMBER):
	    		return False
    		
    		# Get the Person's number and generate a code
    		foundUser = None
    		try:
	    		foundUser = userService.getUserByAttribute("uid", user_name)
	    	except:
	    		printOut('Error retrieving user %s from LDAP' % user_name)
	    		return False
	    	try:
	    		mobile_number = foundUser.getAttribute("mobile")
	    	except:
	    		printOut("Error finding mobile number for 
	    		return False
	    		
	    	# Generate Random six digit code
    		code = random.randint(100000,999999)
    		context.set("code", code)
    		
    		client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
    		bodyParam = BasicNameValuePair("Body", code)
    		toParam = BasicNameValuePair("To", mobile_number)
    		fromParam = BasicNameValuePair("From", FROM_NUMBER)
    		params = ArrayList()
    		params.add(bodyParam)
    		params.add(toParam)
    		params.add(fromParam)
    		    		
			messageFactory = client.getAccount().getMessageFactory()
			message = messageFactory.create(params)
			printOut("Message Sid: %s" % message.getSid())
            return True

        elif (step == 2):
        	code = sessionAttributes.get("code")
        	if (code is None):
                printOut("Failed to find previously sent code")
                return False
            form_passcode = requestParameters.get("passcode")[0].strip()
            if len(form_passcode) != 6:
            	printOut("Invalid passcode length from form: %s" % form_passcode)
            if form_passcode == code:
            	return True
            else:
            	return False
            
        else:
            return False

    def prepareForStep(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print "TwilioSMS. Prepare for Step 1"
            return True
        elif (step == 2):
            print "TwilioSMS. Prepare for Step 2"
            return True
        else:
            return False

	def printOut(s):
		print "TwilioSmsAuthenticator: %s" % s

    def getExtraParametersForStep(self, configurationAttributes, step):
        if (step == 2):
            return Arrays.asList("code")
        return None
        
    def getCountAuthenticationSteps(self, configurationAttributes):
        return 2

    def getPageForStep(self, configurationAttributes, step):
        if (step == 2):
            return "/auth/twilio/twiliologin.xhtml"
        return ""

    def logout(self, configurationAttributes, requestParameters):
        return True
    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
    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 prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)

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

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

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

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

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

            userInum = user.getAttribute("inum")

            registrationRequest = None
            authenticationRequest = None

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

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

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

            return True
    def validateTotpKey(self, secretKey, totpKey):
        localTotpKey = self.generateTotpKey(secretKey)
        if StringHelper.equals(localTotpKey, totpKey):
            return {"result": True}

        return {"result": False}
Example #57
0
    def authenticate(self, configurationAttributes, requestParameters, step): 
        identity = CdiUtil.bean(Identity)
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                userService = CdiUtil.bean(UserService)
                logged_in = authenticationService.authenticate(user_name, user_password)
            if (not logged_in):
                return False
            else:
                find_user_by_uid = authenticationService.getAuthenticatedUser()
                status_attribute_value = userService.getCustomAttribute(find_user_by_uid, "mail")
                user_mail = status_attribute_value.getValue()
                self.setRequestScopedParameters(identity)
                isCompromised = False
                isCompromised = self.is_compromised(user_mail,user_password,configurationAttributes)
                if(isCompromised):
                    identity.setWorkingParameter("pwd_compromised", isCompromised)
                    identity.setWorkingParameter("user_name", user_name)
                    return True
                else: 
                    return True
        elif step == 2:
            print "compromised_password. Authenticate for step 2"
            form_answer_array = requestParameters.get("loginForm:question")
            if ArrayHelper.isEmpty(form_answer_array):
                return False
            form_answer = form_answer_array[0]
            if (form_answer == self.secretanswer):
                return True
            return False
        elif step == 3:
            authenticationService = CdiUtil.bean(AuthenticationService)
            print "compromised_password (with password update). Authenticate for step 3"
            userService = CdiUtil.bean(UserService)
            update_button = requestParameters.get("loginForm:updateButton")
            new_password_array = requestParameters.get("new_password")
            if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty(new_password_array[0]):
                print "compromised_password (with password update). Authenticate for step 3. New password is empty"
                return False
            new_password = new_password_array[0]

            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "compromised_password (with password update). Authenticate for step 3. Failed to determine user name"
                return False

            user_name = user.getUserId()
            print "compromised_password (with password update). Authenticate for step 3. Attempting to set new user '" + user_name + "' password"
            find_user_by_uid = userService.getUser(user_name)
            if (find_user_by_uid == None):
                print "compromised_password (with password update). Authenticate for step 3. Failed to find user"
                return False

            find_user_by_uid.setAttribute("userPassword", new_password)
            userService.updateUser(find_user_by_uid)
            print "compromised_password (with password update). Authenticate for step 3. Password updated successfully"
            logged_in = authenticationService.authenticate(user_name)
            return True