Example #1
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "Registration. Authenticate for step 1"
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        if (StringHelper.isEmptyString(
                self.getUserValueFromAuth("email", requestParameters))):
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            facesMessages.add(FacesMessage.SEVERITY_ERROR,
                              "Please provide your email.")
            return False

        if (StringHelper.isEmptyString(
                self.getUserValueFromAuth("pwd", requestParameters))):
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            facesMessages.add(FacesMessage.SEVERITY_ERROR,
                              "Please provide password.")
            return False

        foundUser = userService.getUserByAttribute(
            "mail", self.getUserValueFromAuth("email", requestParameters))
        if (foundUser == None):
            newUser = User()
            for attributesMappingEntry in self.attributesMapping.entrySet():
                remoteAttribute = attributesMappingEntry.getKey()
                localAttribute = attributesMappingEntry.getValue()
                localAttributeValue = self.getUserValueFromAuth(
                    remoteAttribute, requestParameters)
                if ((localAttribute != None) &
                    (localAttributeValue != "undefined")):
                    print localAttribute + localAttributeValue
                    newUser.setAttribute(localAttribute, localAttributeValue)

            try:
                foundUser = userService.addUser(newUser, True)
                foundUserName = foundUser.getUserId()
                print("Registration: Found user name " + foundUserName)
                userAuthenticated = authenticationService.authenticate(
                    foundUserName)
                print(
                    "Registration: User added successfully and isUserAuthenticated = "
                    + str(userAuthenticated))
            except Exception, err:
                print("Registration: Error in adding user:" + str(err))
                return False
            return userAuthenticated
    def isUserMemberOfGroups(self, credentials, groups):
        userService = CdiUtil.bean(UserService)

        user_name = credentials.getUsername()
        if StringHelper.isEmptyString(user_name):
            return False

        find_user_by_uid = userService.getUser(user_name)

        is_member = False
        member_of_list = find_user_by_uid.getAttributeValues("memberOf")
        if member_of_list == None:
            return is_member

        print member_of_list
        print groups

        for member_of in member_of_list:
            for group in groups:
                if StringHelper.equalsIgnoreCase(
                        group, member_of) or member_of.endswith(group):
                    is_member = True
                    break

        return is_member
Example #3
0
    def checkRequiredAttributes(self, profile, attrs):

        for attr in attrs:
            if (not attr in profile) or StringHelper.isEmptyString(
                    profile[attr]):
                print "Passport. checkRequiredAttributes. Attribute '%s' is missing in profile" % attr
                return False
        return True
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        stringEncrypter = StringEncrypter.defaultInstance()

        context = Contexts.getEventContext()

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

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

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

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

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

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

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

                pairing_id = pairing_process.pairingId
                print "oxPush prepare for step 2. Pairing Id: ", pairing_id
    
                context.set("oxpush_pairing_uid", stringEncrypter.encrypt(pairing_id))
                context.set("oxpush_pairing_code", pairing_process.pairingCode)
                context.set("oxpush_pairing_qr_image", pairing_process.pairingQrImage)
Example #5
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)

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

        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"
                identity.setWorkingParameter("oneid_count_login_steps", 2)
                identity.setWorkingParameter("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

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

            credentials.setUsername(found_user_name)
            credentials.setUser(find_user_by_uid)

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

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

            sessionAttributes = identity.getSessionId().getSessionAttributes()
            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

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

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

            if (not passed_step1):
                return False

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

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

            if (not logged_in):
                return False

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

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

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "OneId. Authenticate for step 2. found_user_name: " + found_user_name

                if StringHelper.equals(user_name, found_user_name):
                    return True

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = Component.getInstance(AuthenticationService)
        userService = Component.getInstance(UserService)

        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 = Component.getInstance(UserService)
                    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
    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
        return None

    def getUserValueFromAuth(self, remote_attr, requestParameters):
        try:
            toBeFeatched = "loginForm:" + remote_attr
            return ServerUtil.getFirstValue(requestParameters, toBeFeatched)
        except Exception, err:
            print("Passport: Exception inside getUserValueFromAuth " + str(err))

    def authenticate(self, configurationAttributes, requestParameters, step):
        try:
            UserId = self.getUserValueFromAuth("userid", requestParameters)
        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):
    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
    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
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()

        stringEncrypter = StringEncrypter.defaultInstance()

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

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

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

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

            if (not logged_in):
                return False

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

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

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

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

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

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

                oxpush_pairing_uid = stringEncrypter.decrypt(oxpush_pairing_uid_array[0])

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

                oxpush_user_uid = pairing_status.deploymentId

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

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

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

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

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

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

            oxpush_user_uid = stringEncrypter.decrypt(oxpush_user_uid_array[0])

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

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

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

            return True
Example #12
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                authenticationService.authenticate(found_user_name)

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

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

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

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

                authenticationService.authenticate(found_user_name)

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

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

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

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

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

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

            if not logged_in:
                return False

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

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

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "CAS2. Authenticate for step 2. found_user_name: " + found_user_name

                if StringHelper.equals(user_name, found_user_name):
                    return True

            return False
        else:
            return False
Example #13
0
            print "Passport-social: Authenticate for step 1. User profile: '%s'" % user_profile_json
            identity.setWorkingParameter("passport_user_profile", user_profile_json)

            uidRemoteAttr = self.getUidRemoteAttr()
            if uidRemoteAttr == None:
                print "Cannot retrieve uid remote attribute"
                return False
            else:
                uidRemoteAttrValue = self.getUserValueFromJwt(user_profile, uidRemoteAttr)
                if "shibboleth" in self.getUserValueFromJwt(user_profile, "provider"):
                    externalUid = "passport-saml:%s" % uidRemoteAttrValue
                else:
                    externalUid = "passport-%s:%s" % (self.getUserValueFromJwt(user_profile, "provider"), uidRemoteAttrValue)

                email = self.getUserValueFromJwt(user_profile, "email")
                if StringHelper.isEmptyString(email):
                    facesMessages = CdiUtil.bean(FacesMessages)
                    facesMessages.setKeepMessages()
                    self.clearFacesMessages(facesContext)
                    facesMessages.add(FacesMessage.SEVERITY_ERROR, "Please provide your email.")

                    print "Passport-social: Email was not received"
                    return False

                userByMail = userService.getUserByAttribute("mail", email)
                userByUid = userService.getUserByAttribute("oxExternalUid", externalUid)

                doUpdate = False
                doAdd = False
                if userByUid!=None:
                    print "User with externalUid '%s' already exists" % externalUid
Example #14
0
            return None

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

        authenticationService = CdiUtil.bean(AuthenticationService)

        try:
            UserId = self.getUserValueFromAuth("userid", requestParameters)
        except Exception, err:
            print "Passport-saml: Error: " + str(err)

        useBasicAuth = StringHelper.isEmptyString(UserId)

        # Use basic method to log in
        if useBasicAuth:
            print "Passport-saml: Basic Authentication"
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()

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

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                userService = CdiUtil.bean(UserService)
                logged_in = authenticationService.authenticate(
Example #15
0
    def attemptAuthentication(self, identity, user_profile, user_profile_json):

        mailRemoteAttr = self.getRemoteAttr("mail")
        uidRemoteAttr = self.getRemoteAttr("uid")
        if not self.checkRequiredAttributes(user_profile,
                                            [uidRemoteAttr, "provider"]):
            return False

        provider = user_profile["provider"]
        if not provider in self.registeredProviders:
            print "Passport. attemptAuthentication. Identity Provider %s not recognized" % provider
            return False

        uidRemoteAttrValue = user_profile[uidRemoteAttr]
        if "saml" in self.registeredProviders[
                provider] and self.registeredProviders[provider]["saml"]:
            # This is for backwards compat. It should be passport-saml-provider:...
            externalUid = "passport-%s:%s" % ("saml", uidRemoteAttrValue)
        else:
            externalUid = "passport-%s:%s" % (provider, uidRemoteAttrValue)

        email = user_profile[mailRemoteAttr]
        userService = CdiUtil.bean(UserService)
        userByUid = userService.getUserByAttribute("oxExternalUid",
                                                   externalUid)

        if userByUid != None and StringHelper.isEmptyString(email):
            # This helps filling the missing email if the user already exists in local LDAP
            email = userByUid.getAttribute("mail")
            if email != None:
                user_profile[mailRemoteAttr] = email

        if StringHelper.isEmptyString(email):
            print "Passport. attemptAuthentication. Email was not received"

            if self.registeredProviders[provider]["emailLinkingSafe"]:
                # Store user profile in session
                identity.setWorkingParameter("passport_user_profile",
                                             user_profile_json)
                return True
            else:
                self.setEmailMessageError()
                return False

        userByMail = userService.getUserByAttribute("mail", email)

        # Determine if we should add entry, update existing, or deny access
        doUpdate = False
        doAdd = False
        if userByUid != None:
            print "User with externalUid '%s' already exists" % externalUid
            if userByMail != None:
                if userByMail.getUserId() == userByUid.getUserId():
                    doUpdate = True
            else:
                doUpdate = True
        else:
            doAdd = userByMail == None

        username = None
        try:
            if doUpdate:
                username = userByUid.getUserId()
                print "Passport. attemptAuthentication. Updating user %s" % username
                self.updateUser(userByUid, user_profile, userService)
            elif doAdd:
                print "Passport. attemptAuthentication. Creating user %s" % externalUid
                newUser = self.addUser(externalUid, user_profile, userService)
                username = newUser.getUserId()
        except:
            print "Exception: ", sys.exc_info()[1]
            print "Passport. attemptAuthentication. Authentication failed"
            return False

        if username == None:
            print "Passport. attemptAuthentication. Authentication attempt was rejected"
            return False
        else:
            logged_in = CdiUtil.bean(AuthenticationService).authenticate(
                username)
            print "Passport. attemptAuthentication. Authentication for %s returned %s" % (
                username, logged_in)
            return logged_in
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        userService = UserService.instance()

        stringEncrypter = StringEncrypter.defaultInstance()

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

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

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

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

            if (not logged_in):
                return False

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

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

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

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

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

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

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

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

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

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

            return True