Esempio n. 1
0
    def parseProviderConfigs(self):

        self.registeredProviders = {}
        try:
            if self.behaveAs == None or self.behaveAs == "social":
                print "Passport. parseProviderConfigs. Adding social providers"
                passportDN = CdiUtil.bean(ConfigurationFactory).getLdapConfiguration().getString("oxpassport_ConfigurationEntryDN")
                entryManager = CdiUtil.bean(AppInitializer).getLdapEntryManager()
                config = LdapOxPassportConfiguration()
                config = entryManager.find(config.getClass(), passportDN).getPassportConfigurations()

                if config != None:
                    for strategy in config:
                        provider = strategy.getStrategy()
                        self.registeredProviders[provider] = { "emailLinkingSafe" : False }
                        for field in strategy.getFieldset():
                            if StringHelper.equalsIgnoreCase(field.getValue1(), "emailLinkingSafe") and StringHelper.equalsIgnoreCase(field.getValue2(), "true"):
                                self.registeredProviders[provider]["emailLinkingSafe"] = True

            if self.behaveAs == None or self.behaveAs == "saml":
                print "Passport. parseProviderConfigs. Adding SAML IDPs"
                f = open("/etc/gluu/conf/passport-saml-config.json", 'r')
                config = json.loads(f.read())

                for provider in config:
                    if "enable" in provider and StringHelper.equalsIgnoreCase(provider["enable"], "true"):
                        self.registeredProviders[provider] = {
                            "emailLinkingSafe" : "emailLinkingSafe" in provider and StringHelper.equalsIgnoreCase(provider["emailLinkingSafe"], "true"),
                            "saml" : True }

        except:
            print "Passport. parseProviderConfigs. An error occurred while building the list of supported authentication providers", sys.exc_info()[1]
    def lockUser(self, user_name, maxCount):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService = CdiUtil.bean(CacheService)
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        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)

        object_to_store = "{'locked': true}"
        cacheService.put(StringHelper.toString(self.lockExpirationTime),
                         "lock_user_" + user_name, object_to_store)
        facesMessages.add(
            FacesMessage.SEVERITY_ERROR,
            "Your account is locked. Please try again after " +
            StringHelper.toString(self.lockExpirationTime) + " secs")

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

        userService = CdiUtil.bean(UserService)
        cacheService = CdiUtil.bean(CacheService)

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

        object_to_store = json.dumps(
            {
                'locked': False,
                'created': LocalDateTime.now().toString()
            },
            separators=(',', ':'))
        cacheService.put(StringHelper.toString(self.lockExpirationTime),
                         "lock_user_" + user_name, object_to_store)

        userService.setCustomAttribute(find_user_by_uid, "gluuStatus",
                                       "active")
        userService.setCustomAttribute(find_user_by_uid,
                                       self.invalidLoginCountAttribute, None)
        updated_user = userService.updateUser(find_user_by_uid)

        print "Basic (lock account). Lock user. User '%s' unlocked" % user_name
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if (step == 1):
            print "Basic (multi login). Authenticate for step 1"

            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            key_value = credentials.getUsername()
            user_password = credentials.getPassword()

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

            return False
        else:
            return False
Esempio n. 5
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        if step == 1:
            print "CAS2. Prepare for step 1"

            requestParameterService = CdiUtil.bean(RequestParameterService)
            httpService = CdiUtil.bean(HttpService)

            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")
            cas_service_request_uri = requestParameterService.parametersAsString(
                parametersMap)
            cas_service_request_uri = self.cas_host + "/login?" + cas_service_request_uri
            if self.cas_extra_opts != None:
                cas_service_request_uri = cas_service_request_uri + "&" + self.cas_extra_opts

            print "CAS2. Prepare for step 1. cas_service_request_uri: " + cas_service_request_uri
            facesService = CdiUtil.bean(FacesService)
            facesService.redirectToExternalURL(cas_service_request_uri)

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

            return True
        else:
            return False
Esempio n. 6
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):

        print "Casa. prepareForStep %s" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            # (re)load the list of external authentication providers currently supported.
            # this avoids touching this custom script if new providers are added or their config simply changes
            self.registeredProviders = self.parseProviderConfigs()
            identity.setWorkingParameter("externalProviders",
                                         json.dumps(self.registeredProviders))
            return True
        else:
            session_attributes = identity.getSessionId().getSessionAttributes()

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()

            if user == None:
                print "Casa. prepareForStep. Cannot retrieve logged user"
                return False

            acr = session_attributes.get("ACR")
            print "Casa. prepareForStep. ACR = %s" % acr
            identity.setWorkingParameter("methods",
                                         self.getAvailMethodsUser(user, acr))

            if acr in self.authenticators:
                module = self.authenticators[acr]
                return module.prepareForStep(module.configAttrs,
                                             requestParameters, step)
            else:
                return False
Esempio n. 7
0
    def validateSessionDeviceStatus(self, client_redirect_uri, session_device_status, user_name = None):
        userService = CdiUtil.bean(UserService)
        deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService)

        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
Esempio n. 8
0
    def prepareForStep(self, configuration_attributes, request_parameters, step):
        print "ThumbSignIn. Inside prepareForStep. Step %d" % step
        identity = CdiUtil.bean(Identity)
        authentication_service = CdiUtil.bean(AuthenticationService)

        identity.setWorkingParameter("ts_host", ts_host)
        identity.setWorkingParameter("ts_statusPath", ts_statusPath)

        self.set_relying_party_login_url(identity)

        if step == 1 or step == 3:
            print "ThumbSignIn. Prepare for step 1"
            self.initialize_thumbsignin(identity, AUTHENTICATE)
            return True

        elif step == 2:
            print "ThumbSignIn. Prepare for step 2"
            if identity.isSetWorkingParameter(USER_LOGIN_FLOW):
                user_login_flow = identity.getWorkingParameter(USER_LOGIN_FLOW)
                print "ThumbSignIn. Value of user_login_flow is %s" % user_login_flow
            user = authentication_service.getAuthenticatedUser()
            if user is None:
                print "ThumbSignIn. Prepare for step 2. Failed to determine user name"
                return False
            user_name = user.getUserId()
            print "ThumbSignIn. Prepare for step 2. user_name: " + user_name
            if user_name is None:
                return False
            identity.setWorkingParameter(USER_ID, user_name)
            self.initialize_thumbsignin(identity, REGISTER + "/" + user_name)
            return True
        else:
            return False
    def validateRecaptcha(self, recaptcha_response):
        print "Cert. Validate recaptcha response"

        facesContext = CdiUtil.bean(FacesContext)
        request = facesContext.getExternalContext().getRequest()

        remoteip = ServerUtil.getIpAddress(request)
        print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip

        httpService = CdiUtil.bean(HttpService)

        http_client = httpService.getHttpsClient()
        http_client_params = http_client.getParams()
        http_client_params.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)

        recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify"
        recaptcha_validation_request = urllib.urlencode({
            "secret":
            self.recaptcha_creds['secret_key'],
            "response":
            recaptcha_response,
            "remoteip":
            remoteip
        })
        recaptcha_validation_headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        }

        try:
            http_service_response = httpService.executePost(
                http_client, recaptcha_validation_url, None,
                recaptcha_validation_headers, recaptcha_validation_request)
            http_response = http_service_response.getHttpResponse()
        except:
            print "Cert. Validate recaptcha response. Exception: ", sys.exc_info(
            )[1]
            return False

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(
                    http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return False

            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if response_string == None:
            print "Cert. Validate recaptcha response. Get empty response from validation server"
            return False

        response = json.loads(response_string)

        return response["success"]
Esempio n. 10
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        authenticationService = CdiUtil.bean(AuthenticationService)

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

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

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

            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "Duo. Prepare for step 2. Failed to determine user name"
                return False
            user_name = user.getUserId()

            duo_sig_request = duo_web.sign_request(self.ikey, self.skey,
                                                   self.akey, user_name)
            print "Duo. Prepare for step 2. duo_sig_request: " + duo_sig_request

            identity.setWorkingParameter("duo_host", duo_host)
            identity.setWorkingParameter("duo_sig_request", duo_sig_request)

            return True
        else:
            return False
Esempio n. 11
0
    def checkUserUniqueness(self, user):
        if self.userEnforceAttributesUniqueness == None:
            return True

        userService = CdiUtil.bean(UserService)

        # 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 = CdiUtil.bean("ldapEntryManager")

        users = userService.getUserBySample(userToSearch, 1)
        if users.size() > 0:
            return False

        return True
Esempio n. 12
0
    def init(self, configurationAttributes):
        print "InWebo. Initialization"

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

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

        iw_cert_password = creds["CERT_PASSWORD"]
        try:
            encryptionService = CdiUtil.bean(EncryptionService)
            iw_cert_password = encryptionService.decrypt(iw_cert_password)
        except:
            return False

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

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

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()
        session_attributes = identity.getSessionId().getSessionAttributes()

        client_id = session_attributes.get("client_id")
        print "Basic (client group). Get client_id: '%s' authorization request" % client_id

        user_groups = self.client_configurations.get(client_id)
        if user_groups == None:
            print "Basic (client group). There is no user groups configuration for client_id '%s'. allow_default_login: %s" % (
                client_id, self.allow_default_login)
            if not self.allow_default_login:
                return False

            result = self.authenticateImpl(credentials, authenticationService)
            return result

        is_member_client_groups = self.isUserMemberOfGroups(
            credentials, user_groups)
        if not is_member_client_groups:
            print "Basic (client group). User '%s' hasn't permissions to log into client_id '%s' application. " % (
                credentials.getUsername(), client_id)
            return False

        result = self.authenticateImpl(credentials, authenticationService)
        return result
Esempio n. 14
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

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

            identity = CdiUtil.bean(Identity)
            identity.setWorkingParameter("pass_authentication", False)

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

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

            if (not logged_in):
                return False

            identity.setWorkingParameter("pass_authentication", True)
            return True
        else:
            return False
Esempio n. 15
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)
        logged_in = False

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

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

            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                try:
                    authNr = HESAuthenticator(self.hideezUrl)
                    hUser = authNr.authN(user_name, user_password)
                    print "Hideez user: Email %s, Name %s, Surname %s" % (hUser.email, hUser.firstName, hUser.lastName)
                    authenticationService.authenticate(user_name)
                    self.hideez_count_login_steps = 1
                    logged_in = True
                except HESAuthenticator.NeedOTPException, ex:
                    identity.setWorkingParameter("hideez_user_name", user_name)
                    identity.setWorkingParameter("hideez_user_password", user_password)
                    self.hideez_count_login_steps = 2
                    logged_in = True
#                except (HESAuthenticator.UserNotFoundException, HESAuthenticator.InvalidCredentialsException, HESAuthenticator.UserIsLockedout), ex:
#                    logged_in = False
#                    print ex.class.name + ex.message
                except Exception, ex:
                    logged_in = False
                    print ex.class.name + ex.message
Esempio n. 16
0
    def parseSocialProviders(self):
        registeredProviders = {}

        try:
            passportDN = CdiUtil.bean(
                ConfigurationFactory).getLdapConfiguration().getString(
                    "oxpassport_ConfigurationEntryDN")
            entryManager = CdiUtil.bean(
                AppInitializer).createLdapEntryManager()
            config = LdapOxPassportConfiguration()
            config = entryManager.find(config.getClass(),
                                       passportDN).getPassportConfigurations()

            if config != None:
                for strategy in config:
                    provider = strategy.getStrategy()
                    registeredProviders[provider] = {"saml": False}

                    property = "logo_img"
                    for field in strategy.getFieldset():
                        if StringHelper.equalsIgnoreCase(
                                field.getValue1(), property):
                            registeredProviders[provider][
                                property] = field.getValue2()
                            break

                    if not property in registeredProviders[provider]:
                        registeredProviders[provider][
                            property] = "img/%s.png" % provider

        except:
            print "Casa. parseProviderConfigs. An error occurred while building the list of supported social authentication providers", sys.exc_info(
            )[1]

        return registeredProviders
Esempio n. 17
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        print "Casa. prepareForStep %s" % str(step)
        if step == 1:
            return True
        else:
            identity = CdiUtil.bean(Identity)
            session_attributes = identity.getSessionId().getSessionAttributes()

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()

            if user == None:
                print "Casa. prepareForStep. Cannot retrieve logged user"
                return False

            acr = session_attributes.get("ACR")
            print "Casa. prepareForStep. ACR = %s" % acr
            identity.setWorkingParameter("methods",
                                         self.getAvailMethodsUser(user, acr))

            if acr in self.authenticators:
                module = self.authenticators[acr]
                return module.prepareForStep(module.configAttrs,
                                             requestParameters, step)
            else:
                return False
    def getSmtpConfig(self):
        '''
        get SMTP config from Gluu Server
        return dict
        '''
       
        smtpconfig = CdiUtil.bean(ConfigurationService).getConfiguration().getSmtpConfiguration()
        
        if smtpconfig is None:
            print "Forgot Password - SMTP CONFIG DOESN'T EXIST - Please configure"

        else:
            print "Forgot Password - SMTP CONFIG FOUND"
            encryptionService = CdiUtil.bean(EncryptionService)
            smtp_config = {
                'host' : smtpconfig.getHost(),
                'port' : smtpconfig.getPort(),
                'user' : smtpconfig.getUserName(),
                'from' : smtpconfig.getFromEmailAddress(),
                'pwd_decrypted' : encryptionService.decrypt(smtpconfig.getPassword()),
                'req_ssl' : smtpconfig.isRequiresSsl(),
                'requires_authentication' : smtpconfig.isRequiresAuthentication(),
                'server_trust' : smtpconfig.isServerTrust()
            }

        return smtp_config
Esempio n. 19
0
    def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes):
        print "Identifier First. getAlternativeAuthenticationMethod"

        identity = CdiUtil.bean(Identity)
        user_name = identity.getCredentials().getUsername()
        print "Identifier First. Inspecting user %s" % user_name

        attributes=identity.getSessionId().getSessionAttributes()
        attributes.put("roUserName", user_name)

        acr = None
        try:
            userService = CdiUtil.bean(UserService)
            foundUser = userService.getUserByAttribute("uid", user_name)

            if foundUser == None:
                print "Identifier First. User does not exist"
                return ""

            attr = configurationAttributes.get("acr_attribute").getValue2()
            acr=foundUser.getAttribute(attr)     
            #acr="u2f" or "otp" or "twilio_sms", etc...
            if acr == None:
                acr = "basic"
        except:
            print "Identifier First. Error looking up user or his preferred method"         

        print "Identifier First. new acr value %s" % acr
        return acr
Esempio n. 20
0
    def getPassportRedirectUrl(self, provider):

        # provider is assumed to exist in self.registeredProviders
        url = None
        try:
            facesContext = CdiUtil.bean(FacesContext)
            tokenEndpoint = "https://%s/passport/token" % facesContext.getExternalContext().getRequest().getServerName()

            httpService = CdiUtil.bean(HttpService)
            httpclient = httpService.getHttpsClient()

            print "Passport. getPassportRedirectUrl. Obtaining token from passport at %s" % tokenEndpoint
            resultResponse = httpService.executeGet(httpclient, tokenEndpoint, Collections.singletonMap("Accept", "text/json"))
            httpResponse = resultResponse.getHttpResponse()
            bytes = httpService.getResponseContent(httpResponse)

            response = httpService.convertEntityToString(bytes)
            print "Passport. getPassportRedirectUrl. Response was %s" % httpResponse.getStatusLine().getStatusCode()

            tokenObj = json.loads(response)

            if self.registeredProviders[provider]["saml"]:
                provider = "saml/" + provider

            url = "/passport/auth/%s/%s" % (provider, tokenObj["token_"])

        except:
            print "Passport. getPassportRedirectUrl. Error building redirect URL: ", sys.exc_info()[1]

        return url
    def authenticate(self, configuration_attributes, request_parameters, step):
        print "ThumbSignIn. Inside authenticate. Step %d" % step
        authentication_service = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)

        identity.setWorkingParameter("ts_host", ts_host)
        identity.setWorkingParameter("ts_statusPath", ts_statusPath)

        if step == 1 or step == 3:
            print "ThumbSignIn. Authenticate for Step %d" % step

            login_flow = ServerUtil.getFirstValue(request_parameters,
                                                  "login_flow")
            print "ThumbSignIn. Value of login_flow parameter is %s" % login_flow

            # Logic for ThumbSignIn Authentication Flow (Either step 1 or step 3)
            if login_flow == THUMBSIGNIN_AUTHENTICATION or login_flow == THUMBSIGNIN_LOGIN_POST_REGISTRATION:
                identity.setWorkingParameter(USER_LOGIN_FLOW, login_flow)
                print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(
                    USER_LOGIN_FLOW)
                logged_in_status = authentication_service.authenticate(
                    self.get_user_id_from_thumbsignin(request_parameters))
                print "ThumbSignIn. logged_in status : %r" % logged_in_status
                return logged_in_status

            # Logic for traditional login flow (step 1)
            print "ThumbSignIn. User credentials login flow"
            identity.setWorkingParameter(USER_LOGIN_FLOW,
                                         THUMBSIGNIN_REGISTRATION)
            print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(
                USER_LOGIN_FLOW)
            logged_in = self.authenticate_user_credentials(
                identity, authentication_service)
            print "ThumbSignIn. Status of User Credentials based Authentication : %r" % logged_in

            # When the traditional login fails, reinitialize the ThumbSignIn data before sending error response to UI
            if not logged_in:
                self.initialize_thumbsignin(identity, AUTHENTICATE)
                return False

            print "ThumbSignIn. Authenticate successful for step %d" % step
            return True

        elif step == 2:
            print "ThumbSignIn. Registration flow (step 2)"
            self.verify_user_login_flow(identity)

            user = self.get_authenticated_user_from_gluu(
                authentication_service)
            if user is None:
                print "ThumbSignIn. Registration flow (step 2). Failed to determine user name"
                return False

            user_name = user.getUserId()
            print "ThumbSignIn. Registration flow (step 2) successful. user_name: %s" % user_name
            return True

        else:
            return False
Esempio n. 22
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()
        session_attributes = identity.getSessionId().getSessionAttributes()

        self.setRequestScopedParameters(identity)

        if step == 1:
            print "OTP. Prepare for step 1"

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

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

            otp_auth_method = session_attributes.get("otp_auth_method")
            print "OTP. Prepare for step 2. otp_auth_method: '%s'" % otp_auth_method

            if otp_auth_method == 'enroll':
                authenticationService = CdiUtil.bean(AuthenticationService)
                user = authenticationService.getAuthenticatedUser()
                if user == None:
                    print "OTP. Prepare for step 2. Failed to load user enty"
                    return False

                if self.otpType == "hotp":
                    otp_secret_key = self.generateSecretHotpKey()
                    otp_enrollment_request = self.generateHotpSecretKeyUri(otp_secret_key, self.otpIssuer, user.getAttribute("displayName"))
                elif self.otpType == "totp":
                    otp_secret_key = self.generateSecretTotpKey()
                    otp_enrollment_request = self.generateTotpSecretKeyUri(otp_secret_key, self.otpIssuer, user.getAttribute("displayName"))
                else:
                    print "OTP. Prepare for step 2. Unknown OTP type: '%s'" % self.otpType
                    return False

                print "OTP. Prepare for step 2. Prepared enrollment request for user: '******'" % user.getUserId()
                identity.setWorkingParameter("otp_secret_key", self.toBase64Url(otp_secret_key))
                identity.setWorkingParameter("otp_enrollment_request", otp_enrollment_request)

            return True
        elif step == 3:
            print "OTP. Prepare for step 3"

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

            otp_auth_method = session_attributes.get("otp_auth_method")
            print "OTP. Prepare for step 3. otp_auth_method: '%s'" % otp_auth_method

            if otp_auth_method == 'enroll':
                return True

        return False
Esempio n. 23
0
    def initSnsPushNotificationService(self, configurationAttributes):
        print "Super-Gluu. Initialize SNS notification services"
        self.pushSnsMode = True

        creds = self.loadPushNotificationCreds(configurationAttributes)
        if creds == None:
            return False

        try:
            sns_creds = creds["sns"]
            android_creds = creds["android"]["sns"]
            ios_creads = creds["ios"]["sns"]
        except:
            print "Super-Gluu. Initialize SNS notification services. Invalid credentials file format"
            return False

        self.pushAndroidService = None
        self.pushAppleService = None
        if not (android_creds["enabled"] or ios_creads["enabled"]):
            print "Super-Gluu. Initialize SNS notification services. SNS disabled for all platforms"
            return False

        sns_access_key = sns_creds["access_key"]
        sns_secret_key = sns_creds["secret_key"]
        sns_region = sns_creds["region"]

        encryptionService = CdiUtil.bean(EncryptionService)

        try:
            sns_access_key = encryptionService.decrypt(sns_access_key)
        except:
            # Ignore exception. Password is not encrypted
            print "Super-Gluu. Initialize SNS notification services. Assuming that 'sns_access_key' in not encrypted"

        try:
            sns_secret_key = encryptionService.decrypt(sns_secret_key)
        except:
            # Ignore exception. Password is not encrypted
            print "Super-Gluu. Initialize SNS notification services. Assuming that 'sns_secret_key' in not encrypted"

        pushSnsService = CdiUtil.bean(PushSnsService)
        snsClient = pushSnsService.createSnsClient(sns_access_key,
                                                   sns_secret_key, sns_region)

        if android_creds["enabled"]:
            self.pushAndroidService = snsClient
            self.pushAndroidPlatformArn = android_creds["platform_arn"]
            print "Super-Gluu. Initialize SNS notification services. Created Android notification service"

        if ios_creads["enabled"]:
            self.pushAppleService = snsClient
            self.pushApplePlatformArn = ios_creads["platform_arn"]
            print "Super-Gluu. Initialize SNS notification services. Created iOS notification service"

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

        return enabled
Esempio n. 24
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        extensionResult = self.extensionPrepareForStep(configurationAttributes,
                                                       requestParameters, step)
        if extensionResult != None:
            return extensionResult

        if (step == 1):
            print "Passport-saml: Prepare for Step 1 method call"
            identity = CdiUtil.bean(Identity)
            sessionId = identity.getSessionId()
            sessionAttribute = sessionId.getSessionAttributes()
            print "Passport-saml: session %s" % sessionAttribute
            oldState = sessionAttribute.get("state")
            if (oldState == None):
                print "Passport-saml: old state is none"
                return True
            else:
                print "Passport-saml: state is obtained"
                try:
                    stateBytes = Base64Util.base64urldecode(oldState)
                    state = StringUtil.fromBytes(stateBytes)
                    stateObj = json.loads(state)
                    print stateObj["provider"]
                    for y in stateObj:
                        print(y, ':', stateObj[y])
                    httpService = CdiUtil.bean(HttpService)
                    facesService = CdiUtil.bean(FacesService)
                    facesContext = CdiUtil.bean(FacesContext)
                    httpclient = httpService.getHttpsClient()
                    headersMap = HashMap()
                    headersMap.put("Accept", "text/json")
                    host = facesContext.getExternalContext().getRequest(
                    ).getServerName()
                    url = "https://" + host + "/passport/token"
                    print "Passport-saml: url %s" % url
                    resultResponse = httpService.executeGet(
                        httpclient, url, headersMap)
                    http_response = resultResponse.getHttpResponse()
                    response_bytes = httpService.getResponseContent(
                        http_response)
                    szResponse = httpService.convertEntityToString(
                        response_bytes)
                    print "Passport-saml: szResponse %s" % szResponse
                    tokenObj = json.loads(szResponse)
                    print "Passport-saml: /passport/auth/saml/" + stateObj[
                        "provider"] + "/" + tokenObj["token_"]
                    facesService.redirectToExternalURL("/passport/auth/saml/" +
                                                       stateObj["provider"] +
                                                       "/" +
                                                       tokenObj["token_"])

                except Exception, err:
                    print str(err)
                    return True
            return True
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if (step == 1):
            print "Basic (multi auth conf). Authenticate for step 1"

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

            metricService = CdiUtil.bean(MetricService)
            timerContext = metricService.getTimer(
                MetricType.OXAUTH_USER_AUTHENTICATION_RATE).time()
            try:
                keyValue = credentials.getUsername()
                userPassword = credentials.getPassword()

                if (StringHelper.isNotEmptyString(keyValue)
                        and StringHelper.isNotEmptyString(userPassword)):
                    for ldapExtendedEntryManager in self.ldapExtendedEntryManagers:
                        ldapConfiguration = ldapExtendedEntryManager[
                            "ldapConfiguration"]
                        ldapEntryManager = ldapExtendedEntryManager[
                            "ldapEntryManager"]
                        loginAttributes = ldapExtendedEntryManager[
                            "loginAttributes"]
                        localLoginAttributes = ldapExtendedEntryManager[
                            "localLoginAttributes"]

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

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

                            loggedIn = authenticationService.authenticate(
                                ldapConfiguration, ldapEntryManager, keyValue,
                                userPassword, primaryKey, localPrimaryKey)
                            if (loggedIn):
                                metricService.incCounter(
                                    MetricType.
                                    OXAUTH_USER_AUTHENTICATION_SUCCESS)
                                return True
                            idx += 1
            finally:
                timerContext.stop()

            metricService.incCounter(
                MetricType.OXAUTH_USER_AUTHENTICATION_FAILURES)

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

        identity = CdiUtil.bean(Identity)
        credentials = identity.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)):
                logged_in = authenticationService.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"
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "Basic (with password update). Authenticate for step 2. Failed to determine user name"
                return False

            user_name = user.getUserId()
            find_user_by_uid = userService.getUser(user_name)

            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]
            find_user_by_uid.setAttribute("userPassword", new_password)
            print "Basic (with password update). Authenticate for step 2. Attempting to set new user '%s' password" % user_name

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

            return True
        else:
            return False
Esempio n. 27
0
    def getNextStep(self, configurationAttributes, requestParameters, step):

        print "Casa. getNextStep called %s" % str(step)
        if step > 1:
            acr = ServerUtil.getFirstValue(requestParameters, "alternativeMethod")
            if acr != None:
                print "Casa. getNextStep. Use alternative method %s" % acr
                CdiUtil.bean(Identity).setWorkingParameter("ACR", acr)
                #retry step with different acr
                return 2

        return -1
Esempio n. 28
0
 def postRegistration(self, user, requestParameters,
                      configurationAttributes):
     print "User registration. Post method"
     appConfiguration = CdiUtil.bean(AppConfiguration)
     servername = appConfiguration.getApplianceUrl()
     mailService = CdiUtil.bean(MailService)
     subject = "Confirmation mail for user registration"
     body = "User Registered for %s. Please Confirm User Registration by clicking url: %s/confirm/registration?code=%s" % (
         user.getMail(), servername, self.guid)
     print body
     mailService.sendMail(user.getMail(), subject, body)
     return True
Esempio n. 29
0
    def getPageForStep(self, configurationAttributes, step):
        print "TwilioSMS. getPageForStep called %s" % step
        print "numbers are %s" % CdiUtil.bean(Identity).getWorkingParameter("numbers")

        defPage = "/casa/twiliosms.xhtml"
        if step == 2:
            if CdiUtil.bean(Identity).getWorkingParameter("numbers") == None:
                return defPage
            else:
                return "/casa/twiliosms_prompt.xhtml"
        elif step == 3:
            return defPage
        return ""
Esempio n. 30
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        extensionResult = self.extensionAuthenticate(configurationAttributes, requestParameters, step)
        if extensionResult != None:
            return extensionResult

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

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