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 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 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)):
                userService = UserService.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 = userService.authenticate(key_value, user_password, primary_key, local_primary_key)
                    if (logged_in):
                        return True
                    i += 1

            return False
        else:
            return False
    def findEnrollments(self, user_name, skipPrefix = True):
        result = []

        userService = UserService.instance()
        user = userService.getUser(user_name, "oxExternalUid")
        if user == None:
            print "OTP. Find enrollments. Failed to find user"
            return result
        
        user_custom_ext_attribute = userService.getCustomAttribute(user, "oxExternalUid")
        if user_custom_ext_attribute == None:
            return result

        otp_prefix = "%s:" % self.otpType
        
        otp_prefix_length = len(otp_prefix) 
        for user_external_uid in user_custom_ext_attribute.getValues():
            index = user_external_uid.find(otp_prefix)
            if index != -1:
                if skipPrefix:
                    enrollment_uid = user_external_uid[otp_prefix_length:]
                else:
                    enrollment_uid = user_external_uid

                result.append(enrollment_uid)
        
        return result
Exemplo n.º 5
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 = 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 findEnrollments(self, user_name, skipPrefix=True):
        result = []

        userService = UserService.instance()
        user = userService.getUser(user_name, "oxExternalUid")
        if user == None:
            print "OTP. Find enrollments. Failed to find user"
            return result

        user_custom_ext_attribute = userService.getCustomAttribute(
            user, "oxExternalUid")
        if user_custom_ext_attribute == None:
            return result

        otp_prefix = "%s:" % self.otpType

        otp_prefix_length = len(otp_prefix)
        for user_external_uid in user_custom_ext_attribute.getValues():
            index = user_external_uid.find(otp_prefix)
            if index != -1:
                if skipPrefix:
                    enrollment_uid = user_external_uid[otp_prefix_length:]
                else:
                    enrollment_uid = user_external_uid

                result.append(enrollment_uid)

        return result
Exemplo n.º 7
0
    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
Exemplo n.º 8
0
    def authenticate(self, configAttributes, requestParams, step):
        userService = UserService.instance()
        authService = AuthenticationService.instance()

        username = requestParams.get('username')[0]
        token = requestParams.get('token')[0]

        if not username or not token:
            print 'Empty input data: username=%s token=%s' % (username, token)
            return False

        # Check if the is user with specified oneid_user_uid
        user_found = userService.getUserByAttribute("username", username)

        if not user_found:
            print "The username %s was not found on the system." % username
            return False

        credentials = Identity.instance().getCredentials()
        credentials.setUsername(username)
        credentials.setUser(user_found)

        secret = base64.b32encode(credentials.getPassword())

        token_generated = from_b32key(secret).generate(t=time.time())

        if int(token) == int(token_generated):
            authService.authenticate(username)
            print "OATH Authentication Successful for %s" % username

        return True
    def checkUserUniqueness(self, user):
        if (self.userEnforceAttributesUniqueness == None):
            return True

        userService = UserService.instance()

        # Prepare user object to search by pattern
        userBaseDn = userService.getDnForUser(None) 

        userToSearch = User()
        userToSearch.setDn(userBaseDn)

        for userAttributeName in self.userEnforceAttributesUniqueness:
            attribute_values_list = user.getAttributeValues(userAttributeName)
            if (attribute_values_list != None) and (attribute_values_list.size() > 0):
                userToSearch.setAttribute(userAttributeName, attribute_values_list)

        ldapEntryManager = Component.getInstance("ldapEntryManager")

        # TODO: Replace with userService.findEntries in CE 2.4.5
        users = ldapEntryManager.findEntries(userToSearch, 1, 1)
        if users.size() > 0:
            return False

        return True
Exemplo n.º 10
0
    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
Exemplo n.º 11
0
    def checkUserUniqueness(self, user):
        if (self.userEnforceAttributesUniqueness == None):
            return True

        userService = UserService.instance()

        # Prepare user object to search by pattern
        userBaseDn = userService.getDnForUser(None)

        userToSearch = User()
        userToSearch.setDn(userBaseDn)

        for userAttributeName in self.userEnforceAttributesUniqueness:
            attribute_values_list = user.getAttributeValues(userAttributeName)
            if (attribute_values_list !=
                    None) and (attribute_values_list.size() > 0):
                userToSearch.setAttribute(userAttributeName,
                                          attribute_values_list)

        ldapEntryManager = Component.getInstance("ldapEntryManager")

        # TODO: Replace with userService.findEntries in CE 2.4.5
        users = ldapEntryManager.findEntries(userToSearch, 1, 1)
        if users.size() > 0:
            return False

        return True
    def authenticate(self, configurationAttributes, requestParameters, step):
        if step == 1:
            print "Basic (lock account). Authenticate for step 1"

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

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                userService = 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 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 update(self, dynamicScopeContext, configurationAttributes):
        print "Permission dynamic scope scope. Update method"

        authorizationGrant = dynamicScopeContext.getAuthorizationGrant()
        user = dynamicScopeContext.getUser()
        jsonWebResponse = dynamicScopeContext.getJsonWebResponse()
        claims = jsonWebResponse.getClaims()

        userService = UserService.instance()
        roles = userService.getCustomAttribute(user, "role")
        if roles != None:
            claims.setClaim("role", roles.getValues())

        return True
Exemplo n.º 16
0
    def update(self, dynamicScopeContext, configurationAttributes):
        print "Dynamic scope. Update method"

        dynamicScopes = dynamicScopeContext.getDynamicScopes()
        authorizationGrant = dynamicScopeContext.getAuthorizationGrant()
        user = dynamicScopeContext.getUser()
        jsonWebResponse = dynamicScopeContext.getJsonWebResponse()
        claims = jsonWebResponse.getClaims()

        # Add work phone if there is scope = work_phone
        userService = UserService.instance()
        workPhone = user.getAttribute("telephoneNumber")
        if (StringHelper.isNotEmpty(workPhone)):
            claims.setClaim("work_phone", workPhone)

        return True
    def setUserAttributeValue(self, user_name, attribute_name, attribute_value):
        if StringHelper.isEmpty(user_name):
            return None

        userService = UserService.instance()

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

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

        return updated_user
Exemplo n.º 18
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
Exemplo n.º 19
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print "Yubicloud. Authenticate for step 1"

            credentials = Identity.instance().getCredentials()
            username = credentials.getUsername()
            otp = credentials.getPassword()

            # Validate otp length
            if len(otp) < 32 or len(otp) > 48:
                print "Yubicloud. Invalid OTP length"
                return False

            user_service = UserService.instance()
            user = user_service.getUser(username)

            public_key = user.getAttribute('yubikeyId')

            # Match the user with the yubikey
            if public_key not in otp:
                print "Yubicloud. Public Key not matching OTP"
                return False

            data = ""
            try:
                nonce = str(uuid.uuid4()).replace("-", "")
                params = urllib.urlencode({
                    "id": self.client_id,
                    "otp": otp,
                    "nonce": nonce
                })
                url = "https://" + self.api_server + "/wsapi/2.0/verify/?" + params
                f = urllib2.urlopen(url)
                data = f.read()
            except Exception as e:
                print "Yubicloud. Exception ", e

            if 'status=OK' in data:
                user_service.authenticate(username)
                print "Yubicloud. Authentication Successful"
                return True

            print "Yubicloud. End of Step 1. Returning False."
            return False
        else:
            return False
    def setUserAttributeValue(self, user_name, attribute_name, attribute_value):
        if StringHelper.isEmpty(user_name):
            return None

        userService = UserService.instance()

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

        userService.setCustomAttribute(
            find_user_by_uid, attribute_name, attribute_value)
        updated_user = userService.updateUser(find_user_by_uid)

        print("Basic (multi auth conf & lock account). Set user attribute. User's '%s' attribute '%s' value is '%s'" % (user_name, attribute_name, attribute_value))  # noqa

        return updated_user
Exemplo n.º 21
0
    def processBasicAuthentication(self, credentials):
        userService = UserService.instance()

        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 None

        find_user_by_uid = userService.getUser(user_name)
        if find_user_by_uid == None:
            print "Super-Gluu. Process basic authentication. Failed to find user '%s'" % user_name
            return None
        
        return find_user_by_uid
Exemplo n.º 22
0
    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

            return True
        else:
            return False
    def getUserAttributeValue(self, user_name, attribute_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = UserService.instance()

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

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

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

        return attribute_value
    def 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):
        if (step == 1):
            print "Yubicloud. Authenticate for step 1"

            credentials = Identity.instance().getCredentials()
            username = credentials.getUsername()
            otp = credentials.getPassword()

            # Validate otp length
            if len(otp) < 32 or len(otp) > 48:
                print "Yubicloud. Invalid OTP length"
                return False

            user_service = UserService.instance()
            user = user_service.getUser(username)

            public_key = user.getAttribute('yubikeyId')

            # Match the user with the yubikey
            if public_key not in otp:
                print "Yubicloud. Public Key not matching OTP"
                return False

            data = ""
            try:
                nonce = str(uuid.uuid4()).replace("-", "")
                params = urllib.urlencode({"id": self.client_id, "otp": otp, "nonce": nonce})
                url = "https://" + self.api_server + "/wsapi/2.0/verify/?" + params
                f = urllib2.urlopen(url)
                data = f.read()
            except Exception as e:
                print "Yubicloud. Exception ", e

            if 'status=OK' in data:
                user_service.authenticate(username)
                print "Yubicloud. Authentication Successful"
                return True

            print "Yubicloud. End of Step 1. Returning False."
            return False
        else:
            return False
    def lockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = UserService.instance()

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

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

        print "Basic (lock account). Lock user. User '%s' locked" % user_name
    def getUserAttributeValue(self, user_name, attribute_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = UserService.instance()

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

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

        attribute_value = custom_attribute_value.getValue()

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

        return attribute_value
Exemplo n.º 28
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print "Shibboleth authenticate for step 1"

            idp_idp_base_uri = configurationAttributes.get("idp_idp_base_uri").getValue2()
            idp_protected_resource_uri = configurationAttributes.get("idp_protected_resource_uri").getValue2()

            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 = self.sb.authenticate(idp_idp_base_uri, idp_protected_resource_uri, user_name, user_password)

            if (not logged_in):
                print "Shibboleth authenticate for step 1. Failed to authenticate user/client"
                return False
            
            if (String(user_name).startsWith("@!")):
                clientService = ClientService.instance()
                client = clientService.getClient(user_name)
                if (client == None):
                    print "Shibboleth authenticate for step 1. Failed to find client in local LDAP"
                    return False
                #TODO: Add client
            else:
                userService = UserService.instance()
                user = userService.getUser(user_name)
                if (user == None):
                    print "Shibboleth authenticate for step 1. Adding new user in local LDAP"
                    user = userService.addDefaultUser(user_name);
    
                credentials.setUser(user);

            return True
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        context.set("pass_authentication", False)

        if 1 <= step <= 3:
            print "Basic (demo reset step). Authenticate for step '%s'" % step

            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

            context.set("pass_authentication", True)
            return True
        else:
            return False
    def lockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = UserService.instance()

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

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

        userService.setCustomAttribute(find_user_by_uid, "gluuStatus",
                                       "inactive")
        updated_user = userService.updateUser(find_user_by_uid)

        print "Basic (lock account). Lock user. User '%s' locked" % user_name
    def findEnrollments(self, credentials):
        result = []

        userService = UserService.instance()
        user_name = credentials.getUsername()
        user = userService.getUser(user_name, "oxExternalUid")
        if user == None:
            print "UAF. Find enrollments. Failed to find user"
            return result
        
        user_custom_ext_attribute = userService.getCustomAttribute(user, "oxExternalUid")
        if user_custom_ext_attribute == None:
            return result
        
        uaf_prefix = "uaf:"
        uaf_prefix_length = len(uaf_prefix) 
        for user_external_uid in user_custom_ext_attribute.getValues():
            index = user_external_uid.find(uaf_prefix)
            if index != -1:
                enrollment_uid = user_external_uid[uaf_prefix_length:]
                result.append(enrollment_uid)
        
        return result
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        context.set("pass_authentication", False)

        if 1 <= step <= 3:
            print "Basic (demo reset step). Authenticate for step '%s'" % step

            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

            context.set("pass_authentication", True)
            return True
        else:
            return False
Exemplo n.º 33
0
    def findEnrollments(self, credentials):
        result = []

        userService = UserService.instance()
        user_name = credentials.getUsername()
        user = userService.getUser(user_name, "oxExternalUid")
        if user == None:
            print "UAF. Find enrollments. Failed to find user"
            return result

        user_custom_ext_attribute = userService.getCustomAttribute(
            user, "oxExternalUid")
        if user_custom_ext_attribute == None:
            return result

        uaf_prefix = "uaf: "
        uaf_prefix_length = len(uaf_prefix)
        for user_external_uid in user_custom_ext_attribute.getValues():
            index = user_external_uid.find(uaf_prefix)
            if index != -1:
                enrollment_uid = user_external_uid[uaf_prefix_length:]
                result.append(enrollment_uid)

        return result
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().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 = UserService.instance()
                logged_in = userService.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

            credentials = Identity.instance().getCredentials()
            user = credentials.getUser()
            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
Exemplo n.º 35
0
    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):

            userService = UserService.instance()

            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

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

            if (user_expDate == None):
                print "Failed to get Date"
                return False

            print "Exp Date is : '" + user_expDate + "' ."

            now = datetime.datetime.now()

            myDate = self.parseDate(user_expDate)

            prevExpDate = self.previousExpDate(myDate)

            expDate = self.newExpirationDate(myDate)

            temp = expDate.strftime("%y%m%d")

            expDate = (expDate + temp + "195000Z")

            if prevExpDate < now:
                print "Basic (with password update). Authenticate for step 2"

                find_user_by_uid.setAttribute("oxPasswordExpirationDate",
                                              expDate)

                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. Attempting to set new user '" + user_name + "' 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 authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()

        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"
        
                context.set("gplus_count_login_steps", 1)
        
                credentials = Identity.instance().getCredentials()
                userName = credentials.getUsername()
                userPassword = credentials.getPassword()
        
                loggedIn = False
                if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                    userService = UserService.instance()
                    loggedIn = userService.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: ", gplusUserUid
            
            if (mapUserDeployment):
                # Use mapping to local IDP user
                print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: gplus:", 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"
                    context.set("gplus_count_login_steps", 2)
                    context.set("gplus_user_uid", gplusUserUid)
                    return True

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName:"******"Google+ Authenticate for step 1. Failed to authenticate user"
                    return False
            
                print "Google+ Authenticate for step 1. Setting count steps to 1"
                context.set("gplus_count_login_steps", 1)

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

                return postLoginResult
            elif (enrollUserDeployment):
                # Use auto enrollment to local IDP
                print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: gplus:", 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", 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", gplusUserUid, " with next attributes", newUser.getCustomAttributes()
 
                    foundUser = userService.addUser(newUser, True)
                    print "Google+ Authenticate for step 1. Added new user with UID", foundUser.getUserId()

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName:"******"Google+ Authenticate for step 1. Failed to authenticate user"
                    return False

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

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

                return postLoginResult
            else:
                # Check if there is user with specified gplusUserUid
                print "Google+ Authenticate for step 1. Attempting to find user by uid:", 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:"******"Google+ Authenticate for step 1. Failed to authenticate user"
                    return False

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

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

                return postLoginResult
        elif (step == 2):
            print "Google+ Authenticate for step 2"
            
            sessionAttributes = context.get("sessionAttributes")
            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

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

            loggedIn = False
            if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                loggedIn = userService.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:", postLoginResult

                return postLoginResult
            else:
                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 2. foundUserName:"******"Google+ Authenticate for step 2. postLoginResult:", postLoginResult
    
                    return postLoginResult
        
            return False
        else:
            return False
Exemplo n.º 37
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        client_redirect_uri = self.getClientRedirecUri(session_attributes)
        if client_redirect_uri == None:
            print "Super-Gluu. Authenticate. redirect_uri is not set"
            return False

        self.setEventContextParameters(context)

        userService = UserService.instance()
        deviceRegistrationService = DeviceRegistrationService.instance()
        if step == 1:
            print "Super-Gluu. Authenticate for step 1"
            if self.oneStep:
  
                session_device_status = self.getSessionDeviceStatus(session_attributes, user_name)
                if session_device_status == None:
                    return

                u2f_device_id = session_device_status['device_id']

                validation_result = self.validateSessionDeviceStatus(client_redirect_uri, session_device_status)
                if validation_result:
                    print "Super-Gluu. Authenticate for step 1. User successfully authenticated with u2f_device '%s'" % u2f_device_id
                else:
                    return False
                    
                if not session_device_status['one_step']:
                    print "Super-Gluu. Authenticate for step 1. u2f_device '%s' is not one step device" % u2f_device_id
                    return False
                    
                # There are two steps only in enrollment mode
                if session_device_status['enroll']:
                    return validation_result

                context.set("super_gluu_count_login_steps", 1)

                user_inum = session_device_status['user_inum']

                u2f_device = deviceRegistrationService.findUserDeviceRegistration(user_inum, u2f_device_id, "oxId")
                if u2f_device == None:
                    print "Super-Gluu. Authenticate for step 1. Failed to load u2f_device '%s'" % u2f_device_id
                    return False

                logged_in = userService.authenticate(user_name)
                if not logged_in:
                    print "Super-Gluu. Authenticate for step 1. Failed to authenticate user '%s'" % user_name
                    return False

                print "Super-Gluu. Authenticate for step 1. User '%s' successfully authenticated with u2f_device '%s'" % (user_name, u2f_device_id)
                
                return True
            elif self.twoStep:
                authenticated_user = self.processBasicAuthentication(credentials)
                if authenticated_user == None:
                    return False
    
                auth_method = 'authenticate'
                enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
                if StringHelper.isNotEmpty(enrollment_mode):
                    auth_method = 'enroll'
                
                if auth_method == 'authenticate':
                    user_inum = userService.getUserInum(authenticated_user)
                    u2f_devices_list = deviceRegistrationService.findUserDeviceRegistrations(user_inum, client_redirect_uri, "oxId")
                    if u2f_devices_list.size() == 0:
                        auth_method = 'enroll'
                        print "Super-Gluu. Authenticate for step 1. There is no U2F '%s' user devices associated with application '%s'. Changing auth_method to '%s'" % (user_name, client_redirect_uri, auth_method)
    
                print "Super-Gluu. Authenticate for step 1. auth_method: '%s'" % auth_method
                
                context.set("super_gluu_auth_method", auth_method)

                return True

            return False
        elif step == 2:
            print "Super-Gluu. Authenticate for step 2"
            session_attributes = context.get("sessionAttributes")

            session_device_status = self.getSessionDeviceStatus(session_attributes, user_name)
            if session_device_status == None:
                return False

            u2f_device_id = session_device_status['device_id']

            # There are two steps only in enrollment mode
            if self.oneStep and session_device_status['enroll']:
                authenticated_user = self.processBasicAuthentication(credentials)
                if authenticated_user == None:
                    return False

                user_inum = userService.getUserInum(authenticated_user)
                
                attach_result = deviceRegistrationService.attachUserDeviceRegistration(user_inum, u2f_device_id)

                print "Super-Gluu. Authenticate for step 2. Result after attaching u2f_device '%s' to user '%s': '%s'" % (u2f_device_id, user_name, attach_result) 

                return attach_result
            elif self.twoStep:
                if user_name == None:
                    print "Super-Gluu. Authenticate for step 2. Failed to determine user name"
                    return False

                validation_result = self.validateSessionDeviceStatus(client_redirect_uri, session_device_status, user_name)
                if validation_result:
                    print "Super-Gluu. Authenticate for step 2. User '%s' successfully authenticated with u2f_device '%s'" % (user_name, u2f_device_id)
                else:
                    return False
                
                super_gluu_request = json.loads(session_device_status['super_gluu_request'])
                auth_method = super_gluu_request['method']
                if auth_method in ['enroll', 'authenticate']:
                    return validation_result

                print "Super-Gluu. Authenticate for step 2. U2F auth_method is invalid"

            return False
        else:
            return False
Exemplo n.º 38
0
    def sendPushNotification(self, client_redirect_uri, user, super_gluu_request):
        if not self.enabledPushNotifications:
            return

        user_name = user.getUserId()
        print "Super-Gluu. 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, client_redirect_uri, "oxId", "oxDeviceData")
        if u2f_devices_list.size() > 0:
            for u2f_device in u2f_devices_list:
                device_data = u2f_device.getDeviceData()

                # Device data which Super-Gluu 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 "Super-Gluu. Send push notification. Apple push notification service is not enabled"
                    else:
                        send_notification = True
                        
                        title = "Super-Gluu"
                        message = "Super-Gluu login request to: %s" % client_redirect_uri

                        additional_fields = { "request" : super_gluu_request }

                        msgBuilder = APNS.newPayload().alertBody(message).alertTitle(title).sound("default")
                        msgBuilder.category('ACTIONABLE').badge(0)
                        msgBuilder.forNewsstand()
                        msgBuilder.customFields(additional_fields)
                        push_message = msgBuilder.build()

                        send_notification_result = self.pushAppleService.push(push_token, push_message)
                        if debug:
                            print "Super-Gluu. Send iOS push notification. token: '%s', message: '%s', send_notification_result: '%s'" % (push_token, push_message, 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 "Super-Gluu. Send push notification. Android push notification service is not enabled"
                    else:
                        send_notification = True

                        title = "Super-Gluu"
                        msgBuilder = Message.Builder().addData("message", super_gluu_request).addData("title", title).collapseKey("single").contentAvailable(True)
                        push_message = msgBuilder.build()

                        send_notification_result = self.pushAndroidService.send(push_message, push_token, 3)
                        if debug:
                            print "Super-Gluu. Send Android push notification. token: '%s', message: '%s', send_notification_result: '%s'" % (push_token, push_message, send_notification_result)


        print "Super-Gluu. Send push notification. send_notification: '%s', send_notification_result: '%s'" % (send_notification, send_notification_result)
Exemplo n.º 39
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()
        httpService = HttpService.instance();

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

        # Create OneID
        authn = OneID(server_flag)

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

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

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

            request = json_data_array[0]
            print "OneId. Authenticate for step 1. request: " + request

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

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

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

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

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

            oneid_user_uid = response['uid']
            print "OneId. Authenticate for step 1. oneid_user_uid: " + oneid_user_uid

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

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

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

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

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

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

            oneid_user_uid = sessionAttributes.get("oneid_user_uid")
            passed_step1 = StringHelper.isNotEmptyString(oneid_user_uid)
            if (not passed_step1):
                return False
#
            credentials = Identity.instance().getCredentials()

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

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

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

            if (not logged_in):
                return False

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

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

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "OneId. Authenticate for step 2. found_user_name: " + found_user_name
    
                if StringHelper.equals(user_name, found_user_name):
                    return True
        
            return False
        else:
            return False
Exemplo n.º 40
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()
        session_attributes = context.get("sessionAttributes")

        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 = 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 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
            context.set("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:
                print "TwilioSMS. Error sending message to Twilio"

            return False
        elif step == 2:
            # Retrieve the session attribute
            print "TwilioSMS. Step 2 SMS/OTP Authentication"
            code = session_attributes.get("code")
            print "TwilioSMS. Code: %s" % str(code)

            if code is None:
                print "TwilioSMS. Failed to find previously sent code"
                return False

            if form_passcode is None:
                print "TwilioSMS. Passcode is empty"
                return False

            if len(form_passcode) != 6:
                print "TwilioSMS. Passcode from response is not 6 digits: %s" % form_passcode
                return False

            if form_passcode == code:
                print "TiwlioSMS, SUCCESS! User entered the same code!"
                return True

            print "TwilioSMS. FAIL! User entered the wrong code! %s != %s" % (
                form_passcode, code)

            return False

        print "TwilioSMS. ERROR: step param not found or != (1|2)"

        return False
        except Exception, err:
            print("Passport: Error: " + str(err))
        useBasicAuth = False
        if (StringHelper.isEmptyString(UserId)):
            useBasicAuth = True

        # Use basic method to log in
        if (useBasicAuth):
            print "Passport: Basic 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)):
                userService = UserService.instance()
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False
            return True

        else:
            try:
                userService = UserService.instance()
                authenticationService = AuthenticationService.instance()
                foundUser = userService.getUserByAttribute("oxExternalUid", self.getUserValueFromAuth("provider",
                                                                                                      requestParameters) + ":" + self.getUserValueFromAuth(
                    self.getUidRemoteAttr(), requestParameters))

                if (foundUser == None):
Exemplo n.º 42
0
    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: '%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 "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: '%s'" % saml_response_name_id

            saml_response_attributes = samlResponse.getAttributes()
            print "Saml. Authenticate for step 1. attributes: '%s'" % 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: '%s'" % 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: '%s'" % 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: '%s'" % 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: '%s'" % 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 '%s'" % currentAttributesMapping

                    newUser = User()

                    # Set custom object classes
                    if self.userObjectClasses != None:
                        print "Saml. Authenticate for step 1. 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. Authenticate for step 1. Trying to map '%s' into '%s'" % (
                                idpAttribute, localAttribute)

                        localAttributeValue = saml_response_normalized_attributes.get(
                            idpAttribute)
                        if (localAttributeValue != None):
                            if self.debugEnrollment:
                                print "Saml. Authenticate for step 1. Setting attribute '%s' value '%s'" % (
                                    localAttribute, localAttributeValue)
                            newUser.setAttribute(localAttribute,
                                                 localAttributeValue)

                    newUser.setAttribute("oxExternalUid",
                                         "saml:" + saml_user_uid)
                    print "Saml. 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 "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getAttribute(
                            "uid")
                        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 "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId(
                    )

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

                user_authenticated = authenticationService.authenticate(
                    found_user_name)
                if (user_authenticated == False):
                    print "Saml. Authenticate for step 1. Failed to authenticate user: '******'" % found_user_name
                    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: '%s'" % 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()

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

                    customAttributes = ArrayList()
                    for key in saml_response_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)

                    user_unique = self.checkUserUniqueness(user)
                    if not user_unique:
                        print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getAttribute(
                            "uid")
                        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(user, True)
                    print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId(
                    )

                found_user_name = find_user_by_uid.getUserId()
                print "Saml. Authenticate for step 1. found_user_name: '%s'" % 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: '%s'" % 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: '%s'" % 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: '%s'" % 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: '%s'" % 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: '%s'" % 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: '%s'" % 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: '%s'" % post_login_result

                    return post_login_result

            return False
        else:
            return False
Exemplo n.º 43
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()

        iw_api_uri = configurationAttributes.get("iw_api_uri").getValue2()
        iw_service_id = configurationAttributes.get("iw_service_id").getValue2()
        iw_helium_enabled = Boolean(configurationAttributes.get("iw_helium_enabled").getValue2()).booleanValue()

        if (iw_helium_enabled):
            context.set("iw_count_login_steps", 1)

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

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

            print "InWebo. Authenticate for step 1. iw_helium_enabled:", iw_helium_enabled
            user_password = credentials.getPassword()
            if (iw_helium_enabled):
                login_array = requestParameters.get("login")
                if ArrayHelper.isEmpty(login_array):
                    print "InWebo. Authenticate for step 1. login is empty"
                    return False
    
                user_name = login_array[0]

                password_array = requestParameters.get("password")
                if ArrayHelper.isEmpty(password_array):
                    print "InWebo. Authenticate for step 1. password is empty"
                    return False
    
                user_password = password_array[0]

                response_validation = self.validateInweboToken(iw_api_uri, iw_service_id, user_name, user_password)
                if (not response_validation):
                    return False

                logged_in = False
                if (StringHelper.isNotEmptyString(user_name)):
                    userService = UserService.instance()
                    logged_in = userService.authenticate(user_name)
    
                return logged_in
            else:
                logged_in = False
                if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                    userService = UserService.instance()
                    logged_in = userService.authenticate(user_name, user_password)
    
                return logged_in
            
            return True
        elif (step == 2):
            print "InWebo. Authenticate for step 2"

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

            iw_token_array = requestParameters.get("iw_token")
            if ArrayHelper.isEmpty(iw_token_array):
                print "InWebo. Authenticate for step 2. iw_token is empty"
                return False

            iw_token = iw_token_array[0]

            response_validation = self.validateInweboToken(iw_api_uri, iw_service_id, user_name, iw_token)
            
            return response_validation
        else:
            return False
Exemplo n.º 44
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()

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

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

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

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

            if (not logged_in):
                return False

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

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

            return True
        elif (step == 2):
            print "Toopher. 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("toopher_user_uid"):
                print "Toopher. Authenticate for step 2. toopher_user_uid is empty"

                # Pair with phone
                pairing_phrase_array = requestParameters.get("pairing_phrase")
                if ArrayHelper.isEmpty(pairing_phrase_array):
                    print "Toopher. Authenticate for step 2. pairing_phrase is empty"
                    return False

                pairing_phrase = pairing_phrase_array[0]
                try:
                    pairing_status = self.tapi.pair(pairing_phrase, user_name)
                    toopher_user_uid = pairing_status.id
                except RequestError, err:
                    print "Toopher. Authenticate for step 2. Failed pair with phone: ", err
                    return False

                pairing_result = self.checkPairingStatus(
                    toopher_user_uid, toopher_user_timeout)

                if (not pairing_result):
                    print "Toopher. Authenticate for step 2. The pairing has not been authorized by the phone yet"
                    return False

                print "Toopher. Authenticate for step 2. Storing toopher_user_uid in user entry", toopher_user_uid

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

                context.set("toopher_user_uid", toopher_user_uid)
            else:
                toopher_user_uid = sessionAttributes.get("toopher_user_uid")

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

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

        stringEncrypter = StringEncrypter.defaultInstance()

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

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

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

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

            # Validate ticket
            request = FacesContext.getCurrentInstance().getExternalContext().getRequest()

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

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

            http_client = httpService.getHttpsClientTrustAll();
            http_response = httpService.executeGet(http_client, cas_service_request_uri)
            validation_content = httpService.convertEntityToString(httpService.getResponseContent(http_response))
            print "CAS2 authenticate for step 1. validation_content: " + validation_content
            if StringHelper.isEmpty(validation_content):
                print "CAS2 authenticate for step 1. Ticket validation response is invalid"
                return False

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

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

            if (cas_map_user):
                print "CAS2 authenticate for step 1. Attempting to find user by oxExternalUid: cas2:" + cas2_user_uid

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

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

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

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

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

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

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

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

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

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

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

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

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

            if (not logged_in):
                return False

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

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

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "CAS2 authenticate for step 2. found_user_name: " + found_user_name
    
                if StringHelper.equals(user_name, found_user_name):
                    return True
        
            return False
        else:
            return False
Exemplo n.º 46
0
    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):

            userService = UserService.instance()

            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

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

            if (user_expDate == None):
                    print "Failed to get Date"
                    return False

            print "Exp Date is : '" + user_expDate + "' ."

            now = datetime.datetime.now()

            myDate = self.parseDate(user_expDate)

            prevExpDate = self.previousExpDate(myDate)

            expDate = self.newExpirationDate(myDate)

            temp = expDate.strftime("%y%m%d")

            expDate = (expDate + temp + "195000Z")

            if prevExpDate < now:
                print "Basic (with password update). Authenticate for step 2"

                find_user_by_uid.setAttribute("oxPasswordExpirationDate", expDate)

                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. Attempting to set new user '" + user_name + "' password"


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

                return True
        else:
            return False
Exemplo n.º 47
0
    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: '%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 "Saml. Authenticate for step 1. saml_response isn't valid"

            saml_response_attributes = samlResponse.getAttributes()
            print "Saml. 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 "Saml. 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 "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: '%s'" % 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: '%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 "Saml. 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 "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP"

                    print "Saml. 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 "Saml. 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 "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId(
                    )
                else:
                    if self.updateUser:
                        print "Saml. 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 "Saml. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid

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

                user_authenticated = authenticationService.authenticate(
                    found_user_name)
                if (user_authenticated == False):
                    print "Saml. Authenticate for step 1. Failed to authenticate user: '******'" % found_user_name
                    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: '%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 "Saml. 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 "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP"

                    print "Saml. 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 "Saml. 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 "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId(
                    )
                else:
                    if self.updateUser:
                        print "Saml. 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 "Saml. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid

                found_user_name = find_user_by_uid.getUserId()
                print "Saml. Authenticate for step 1. found_user_name: '%s'" % 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: '%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 "Saml. 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 "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: '%s'" % 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: '%s'" % 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:%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 "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: '%s'" % 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: '%s'" % 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: '%s'" % post_login_result

                    return post_login_result

            return False
        else:
            return False
Exemplo n.º 48
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()

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

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

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

            # Get user entry from credentials
            authenticationService = AuthenticationService.instance()
            credentials_user = authenticationService.getAuthenticatedUser()

            userService = UserService.instance()
            phone_number_with_country_code_attr = userService.getCustomAttribute(
                credentials_user, pf_phone_number_attr)
            if (phone_number_with_country_code_attr == None):
                print "PhoneFactor. Authenticate for step 2. There is no phone number: ", user_name
                return False

            phone_number_with_country_code = phone_number_with_country_code_attr.getValue(
            )
            if (phone_number_with_country_code == None):
                print "PhoneFactor. Authenticate for step 2. There is no phone number: ", user_name
                return False

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

            phone_number_with_country_code_array = string.split(
                phone_number_with_country_code, pf_country_delimiter, 1)

            phone_number_with_country_code_array_len = len(
                phone_number_with_country_code_array)

            if (phone_number_with_country_code_array_len == 1):
                country_code = ""
                phone_number = phone_number_with_country_code_array[0]
            else:
                country_code = phone_number_with_country_code_array[0]
                phone_number = phone_number_with_country_code_array[1]

            print "PhoneFactor. Authenticate for step 2. user_name: ", user_name, ", country_code: ", country_code, ", phone_number: ", phone_number

            pf_auth_result = None
            try:
                pf_auth_result = self.pf.authenticate(user_name, country_code,
                                                      phone_number, None, None,
                                                      None)
            except SecurityException, err:
                print "PhoneFactor. Authenticate for step 2. BAD AUTH -- Security issue: ", err
            except TimeoutException, err:
                print "PhoneFactor. Authenticate for step 2. BAD AUTH -- Server timeout: ", err
Exemplo n.º 49
0
    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
Exemplo n.º 50
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()

        iw_api_uri = configurationAttributes.get("iw_api_uri").getValue2()
        iw_service_id = configurationAttributes.get(
            "iw_service_id").getValue2()
        iw_helium_enabled = Boolean(
            configurationAttributes.get(
                "iw_helium_enabled").getValue2()).booleanValue()

        if (iw_helium_enabled):
            context.set("iw_count_login_steps", 1)

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

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

            print "InWebo. Authenticate for step 1. iw_helium_enabled:", iw_helium_enabled
            user_password = credentials.getPassword()
            if (iw_helium_enabled):
                login_array = requestParameters.get("login")
                if ArrayHelper.isEmpty(login_array):
                    print "InWebo. Authenticate for step 1. login is empty"
                    return False

                user_name = login_array[0]

                password_array = requestParameters.get("password")
                if ArrayHelper.isEmpty(password_array):
                    print "InWebo. Authenticate for step 1. password is empty"
                    return False

                user_password = password_array[0]

                response_validation = self.validateInweboToken(
                    iw_api_uri, iw_service_id, user_name, user_password)
                if (not response_validation):
                    return False

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

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

                return logged_in

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

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

            iw_token_array = requestParameters.get("iw_token")
            if ArrayHelper.isEmpty(iw_token_array):
                print "InWebo. Authenticate for step 2. iw_token is empty"
                return False

            iw_token = iw_token_array[0]

            response_validation = self.validateInweboToken(
                iw_api_uri, iw_service_id, user_name, iw_token)

            return response_validation
        else:
            return False
Exemplo n.º 51
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        session_attributes = context.get("sessionAttributes")

        self.setEventContextParameters(context)

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

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

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

            if uaf_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 1. There is no UAF enrollment for user '%s'. Changing uaf_auth_method to '%s'" % (
                        user_name, uaf_auth_method)

            print "UAF. Authenticate for step 1. uaf_auth_method: '%s'" % uaf_auth_method

            context.set("uaf_auth_method", uaf_auth_method)

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

            session_state = SessionStateService.instance(
            ).getSessionStateFromCookie()
            if StringHelper.isEmpty(session_state):
                print "UAF. Prepare for step 2. Failed to determine session_state"
                return False

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

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

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

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

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

                # Prepare STATUS_OBB
                uaf_obb_start_response_json = json.loads(
                    uaf_obb_start_response)
                uaf_obb_status_request_dictionary = {
                    "operation":
                    "STATUS_%s" % uaf_obb_auth_method,
                    "userName":
                    user_name,
                    "needDetails":
                    1,
                    "oobStatusHandle":
                    uaf_obb_start_response_json["oobStatusHandle"],
                }

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

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

                print "UAF. Authenticate for step 2. Get STATUS response: '%s'" % uaf_status_obb_response
                uaf_status_obb_response_json = json.loads(
                    uaf_status_obb_response)

                if uaf_status_obb_response_json["statusCode"] != 4000:
                    print "UAF. Authenticate for step 2. UAF operation status is invalid. statusCode: '%s'" % uaf_status_obb_response_json[
                        "statusCode"]
                    return False

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

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

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

            if uaf_auth_method == "authenticate":
                # Validate if user used device with same keYHandle
                user_enrollments = self.findEnrollments(credentials)
                if len(user_enrollments) == 0:
                    uaf_auth_method = "enroll"
                    print "UAF. Authenticate for step 2. There is no UAF enrollment for user '%s'." % user_name
                    return False

                for user_enrollment in user_enrollments:
                    if StringHelper.equalsIgnoreCase(user_enrollment,
                                                     uaf_user_device_handle):
                        print "UAF. Authenticate for step 2. There is UAF enrollment for user '%s'. User authenticated successfully" % user_name
                        return True
            else:
                userService = UserService.instance()

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

                    return True

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()

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

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

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

            # Get user entry from credentials
            credentials_user = credentials.getUser()
            
            userService = UserService.instance()
            phone_number_with_country_code_attr = userService.getCustomAttribute(credentials_user, pf_phone_number_attr)
            if (phone_number_with_country_code_attr == None):
                print "PhoneFactor. Authenticate for step 2. There is no phone number: ", user_name
                return False
            
            phone_number_with_country_code = phone_number_with_country_code_attr.getValue()
            if (phone_number_with_country_code == None):
                print "PhoneFactor. Authenticate for step 2. There is no phone number: ", user_name
                return False

            pf_country_delimiter = configurationAttributes.get("pf_country_delimiter").getValue2()
            
            phone_number_with_country_code_array = string.split(phone_number_with_country_code, pf_country_delimiter, 1)
            
            phone_number_with_country_code_array_len = len(phone_number_with_country_code_array)
            
            if (phone_number_with_country_code_array_len == 1):
                country_code = ""
                phone_number = phone_number_with_country_code_array[0]
            else:
                country_code = phone_number_with_country_code_array[0]
                phone_number = phone_number_with_country_code_array[1]

            print "PhoneFactor. Authenticate for step 2. user_name: ", user_name, ", country_code: ", country_code, ", phone_number: ", phone_number

            pf_auth_result = None
            try:
                pf_auth_result = self.pf.authenticate(user_name, country_code, phone_number, None, None, None)
            except SecurityException, err:
                print "PhoneFactor. Authenticate for step 2. BAD AUTH -- Security issue: ", err
            except TimeoutException, err:
                print "PhoneFactor. Authenticate for step 2. BAD AUTH -- Server timeout: ", err
    def authenticate(self, configurationAttributes, requestParameters, step):
        credentials = Identity.instance().getCredentials()
        user_name = credentials.getUsername()

        context = Contexts.getEventContext()
        userService = UserService.instance()

        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"
                context.set("cert_selected", False)

                # Return True to inform user how to reset workflow
                return True
            else:
                context.set("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
                context.set("cert_valid", False)

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

            context.set("cert_valid", True)

            # Calculate certificate fingerprint
            x509CertificateFingerprint = self.calculateCertificateFingerprint(
                x509Certificate)
            context.set("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"
                    context.set("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"
                    context.set("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"
            context.set("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

            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

            # 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
Exemplo n.º 54
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()

        encryptionService = EncryptionService.instance()

        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"
        
                context.set("gplus_count_login_steps", 1)
        
                credentials = Identity.instance().getCredentials()
                userName = credentials.getUsername()
                userPassword = credentials.getPassword()
        
                loggedIn = False
                if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                    userService = UserService.instance()
                    loggedIn = userService.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: ", gplusUserUid
            
            if (mapUserDeployment):
                # Use mapping to local IDP user
                print "Google+ authenticate for step 1. Attempting to find user by oxExternalUid: gplus:", 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"
                    context.set("gplus_count_login_steps", 2)
                    context.set("gplus_user_uid", encryptionService.encrypt(gplusUserUid))
                    return True

                foundUserName = foundUser.getUserId()
                print "Google+ authenticate for step 1. foundUserName:"******"Google+ authenticate for step 1. Failed to authenticate user"
                    return False
            
                print "Google+ authenticate for step 1. Setting count steps to 1"
                context.set("gplus_count_login_steps", 1)

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ authenticate for step 1. postLoginResult:", postLoginResult

                return postLoginResult
            elif (enrollUserDeployment):
                # Use auto enrollment to local IDP
                print "Google+ authenticate for step 1. Attempting to find user by oxExternalUid: gplus:", 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", currentAttributesMapping
 
                    newUser = User()
                    for attributesMappingEntry in currentAttributesMapping.entrySet():
                        idpAttribute = attributesMappingEntry.getKey()
                        localAttribute = attributesMappingEntry.getValue()
 
                        localAttributeValue = gplusResponseNormalizedAttributes.get(idpAttribute)
                        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", gplusUserUid, " with next attributes", newUser.getCustomAttributes()
 
                    foundUser = userService.addUser(newUser)
                    print "Google+ authenticate for step 1. Added new user with UID", foundUser.getUserId()

                foundUserName = foundUser.getUserId()
                print "Google+ authenticate for step 1. foundUserName:"******"Google+ authenticate for step 1. Failed to authenticate user"
                    return False

                print "Google+ authenticate for step 1. Setting count steps to 1"
                context.set("gplus_count_login_steps", 1)

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ authenticate for step 1. postLoginResult:", postLoginResult

                return postLoginResult
            else:
                # Check if the is user with specified gplusUserUid
                print "Google+ authenticate for step 1. Attempting to find user by uid:", 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:"******"Google+ authenticate for step 1. Failed to authenticate user"
                    return False

                print "Google+ authenticate for step 1. Setting count steps to 1"
                context.set("gplus_count_login_steps", 1)

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ authenticate for step 1. postLoginResult:", postLoginResult

                return postLoginResult
        elif (step == 2):
            print "Google+ authenticate for step 2"
            
            gplusUserUidArray = requestParameters.get("gplus_user_uid")
            if ArrayHelper.isEmpty(gplusUserUidArray):
                print "Google+ authenticate for step 2. gplus_user_uid is empty"
                return False

            gplusUserUid = encryptionService.decrypt(gplusUserUidArray[0])
            passedStep1 = StringHelper.isNotEmptyString(gplusUserUid)
            if (not passedStep1):
                return False

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

            loggedIn = False
            if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                loggedIn = userService.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:", postLoginResult

                return postLoginResult
            else:
                foundUserName = foundUser.getUserId()
                print "Google+ authenticate for step 2. foundUserName:"******"Google+ authenticate for step 2. postLoginResult:", postLoginResult
    
                    return postLoginResult
        
            return False
        else:
            return False