def getCountAuthenticationSteps(self, configurationAttributes): identity = CdiUtil.bean(Identity) if identity.isSetWorkingParameter("otp_count_login_steps"): return StringHelper.toInteger( "%s" % identity.getWorkingParameter("otp_count_login_steps")) else: return 2
def getNextStep(self, configurationAttributes, requestParameters, step): if step == 1: identity = CdiUtil.bean(Identity) provider = identity.getWorkingParameter("selectedProvider") if provider != None: return 1 return -1
def init(self, configurationAttributes): print "CAS2. Initialization" if not configurationAttributes.containsKey("cas_host"): print "CAS2. Initialization. Parameter 'cas_host' is missing" return False self.cas_host = configurationAttributes.get("cas_host").getValue2() self.cas_extra_opts = None if configurationAttributes.containsKey("cas_extra_opts"): self.cas_extra_opts = configurationAttributes.get( "cas_extra_opts").getValue2() self.cas_renew_opt = False if configurationAttributes.containsKey("cas_renew_opt"): self.cas_renew_opt = StringHelper.toBoolean( configurationAttributes.get("cas_renew_opt").getValue2(), False) self.cas_map_user = False if configurationAttributes.containsKey("cas_map_user"): self.cas_map_user = StringHelper.toBoolean( configurationAttributes.get("cas_map_user").getValue2(), False) self.cas_enable_server_validation = False if (configurationAttributes.containsKey("cas_validation_uri") and configurationAttributes.containsKey("cas_validation_pattern") and configurationAttributes.containsKey("cas_validation_timeout")): print "CAS2. Initialization. Configuring checker client" self.cas_enable_server_validation = True self.cas_validation_uri = configurationAttributes.get( "cas_validation_uri").getValue2() self.cas_validation_pattern = configurationAttributes.get( "cas_validation_pattern").getValue2() cas_validation_timeout = int( configurationAttributes.get( "cas_validation_timeout").getValue2()) * 1000 httpService = CdiUtil.bean(HttpService) self.http_client = httpService.getHttpsClient() self.http_client_params = self.http_client.getParams() self.http_client_params.setIntParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, cas_validation_timeout) self.cas_alt_auth_mode = None if configurationAttributes.containsKey("cas_alt_auth_mode"): self.cas_alt_auth_mode = configurationAttributes.get( "cas_alt_auth_mode").getValue2() print "CAS2. Initialized successfully" return True
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) authenticationService = CdiUtil.bean(AuthenticationService) 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. Prepare for step 1" facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() validation_page = request.getContextPath( ) + "/postlogin?" + "request_uri=&" + authenticationService.parametersAsString( ) print "OneId. Prepare for step 1. validation_page: " + validation_page oneid_login_button = authn.draw_signin_button( validation_page, callback_attrs, True) print "OneId. Prepare for step 1. oneid_login_button: " + oneid_login_button identity.setWorkingParameter("oneid_login_button", oneid_login_button) identity.setWorkingParameter("oneid_script_header", authn.script_header) identity.setWorkingParameter("oneid_form_script", authn.oneid_form_script) return True elif (step == 2): print "OneId. Prepare for step 2" return True else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): extensionResult = self.extensionPrepareForStep(configurationAttributes, requestParameters, step) if extensionResult != None: return extensionResult print "Passport. prepareForStep called %s" % str(step) identity = CdiUtil.bean(Identity) if step == 1: # This param is needed in passportlogin.xhtml identity.setWorkingParameter("behaviour", self.behaveAs) #re-read the strategies config (for instance to know which strategies have enabled the email account linking) self.parseProviderConfigs() providerParam = self.customAuthzParameter url = None #this param could have been set previously in authenticate step if current step is being retried provider = identity.getWorkingParameter("selectedProvider") if provider != None: url = self.getPassportRedirectUrl(provider) identity.setWorkingParameter("selectedProvider", None) elif providerParam != None: sessionAttributes = identity.getSessionId().getSessionAttributes() paramValue = sessionAttributes.get(providerParam) if paramValue != None: print "Passport. prepareForStep. Found value in custom param of authorization request: %s" % paramValue provider = self.getProviderFromJson(paramValue) if provider == None: print "Passport. prepareForStep. A provider value could not be extracted from custom authorization request parameter" elif not provider in self.registeredProviders: print "Passport. prepareForStep. Provider '%s' not part of known configured IDPs/OPs" % provider else: url = self.getPassportRedirectUrl(provider) if url == None: print "Passport. prepareForStep. A page to manually select an identity provider will be shown" else: facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(url) return True
def getGeolocation(self, identity): session_attributes = identity.getSessionId().getSessionAttributes() if session_attributes.containsKey("remote_ip"): remote_ip = session_attributes.get("remote_ip") if StringHelper.isNotEmpty(remote_ip): httpService = CdiUtil.bean(HttpService) http_client = httpService.getHttpsClient() http_client_params = http_client.getParams() http_client_params.setIntParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 4 * 1000) geolocation_service_url = "http://ip-api.com/json/%s?fields=country,city,status,message" % remote_ip geolocation_service_headers = {"Accept": "application/json"} try: http_service_response = httpService.executeGet( http_client, geolocation_service_url, geolocation_service_headers) http_response = http_service_response.getHttpResponse() except: print "Casa. Determine remote location. Exception: ", sys.exc_info( )[1] return None try: if not httpService.isResponseStastusCodeOk(http_response): print "Casa. Determine remote location. Get non 200 OK response from server:", str( http_response.getStatusLine().getStatusCode()) httpService.consume(http_response) return None response_bytes = httpService.getResponseContent( http_response) response_string = httpService.convertEntityToString( response_bytes, Charset.forName("UTF-8")) httpService.consume(http_response) finally: http_service_response.closeConnection() if response_string == None: print "Casa. Determine remote location. Get empty response from location server" return None response = json.loads(response_string) if not StringHelper.equalsIgnoreCase(response['status'], "success"): print "Casa. Determine remote location. Get response with status: '%s'" % response[ 'status'] return None return response return None
def getCountAuthenticationSteps(self, configurationAttributes): identity = CdiUtil.bean(Identity) self.setRequestScopedParameters(identity) self.setRequestScopedParameters(identity) session_attributes = identity.getSessionId().getSessionAttributes() pwdcompromised = session_attributes.get("pwd_compromised") if (pwdcompromised != None): return 3 return 1
def getCountAuthenticationSteps(self, configurationAttributes): identity = CdiUtil.bean(Identity) session_attributes = identity.getSessionState().getSessionAttributes() if session_attributes.containsKey("otp_count_login_steps"): return StringHelper.toInteger( session_attributes.get("otp_count_login_steps")) else: return 2
def postRegistration(self, user, requestParameters, configurationAttributes): print "User registration. Post method" appConfiguration = CdiUtil.bean(AppConfiguration) hostName = appConfiguration.getApplianceUrl() externalContext = CdiUtil.bean(ExternalContext) contextPath = externalContext.getRequest().getContextPath() mailService = CdiUtil.bean(MailService) subject = "Confirmation mail for user registration" body = "User Registered for %s. Please Confirm User Registration by clicking url: %s%s/confirm/registration?code=%s" % ( user.getMail(), hostName, contextPath, self.guid) print "User registration. Post method. Attempting to send e-mail to '%s' message '%s'" % ( user.getMail(), body) mailService.sendMail(user.getMail(), subject, body) return True
def authenticate(self, configurationAttributes, requestParameters, step): if (step == 1): print "Yubicloud. Authenticate for step 1" identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() username = credentials.getUsername() otp = credentials.getPassword() # Validate otp length if len(otp) < 32 or len(otp) > 48: print "Yubicloud. Invalid OTP length" return False user_service = CdiUtil.bean(UserService) user = user_service.getUser(username) public_key = user.getAttribute('yubikeyId') # Match the user with the yubikey if public_key not in otp: print "Yubicloud. Public Key not matching OTP" return False data = "" try: nonce = str(uuid.uuid4()).replace("-", "") params = urllib.urlencode({"id": self.client_id, "otp": otp, "nonce": nonce}) url = "https://" + self.api_server + "/wsapi/2.0/verify/?" + params f = urllib2.urlopen(url) data = f.read() except Exception as e: print "Yubicloud. Exception ", e if 'status=OK' in data: user_service.authenticate(username) print "Yubicloud. Authentication Successful" return True print "Yubicloud. End of Step 1. Returning False." return False else: return False
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if step == 1: print "Basic (lock account). Authenticate for step 1" 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)): try: logged_in = authenticationService.authenticate( user_name, user_password) except AuthenticationException: print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name if (not logged_in): countInvalidLoginArributeValue = self.getUserAttributeValue( user_name, self.invalidLoginCountAttribute) countInvalidLogin = StringHelper.toInteger( countInvalidLoginArributeValue, 0) if countInvalidLogin < self.maximumInvalidLoginAttemps: countInvalidLogin = countInvalidLogin + 1 self.setUserAttributeValue( user_name, self.invalidLoginCountAttribute, StringHelper.toString(countInvalidLogin)) if countInvalidLogin >= self.maximumInvalidLoginAttemps: self.lockUser(user_name) return False self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(0)) return True else: return False
def initRecaptcha(self, configurationAttributes): print "Cert. Initialize recaptcha" if not configurationAttributes.containsKey("credentials_file"): return False cert_creds_file = configurationAttributes.get( "credentials_file").getValue2() # Load credentials from file f = open(cert_creds_file, 'r') try: creds = json.loads(f.read()) except: print "Cert. Initialize recaptcha. Failed to load credentials from file: %s" % cert_creds_file return False finally: f.close() try: recaptcha_creds = creds["recaptcha"] except: print "Cert. Initialize recaptcha. Invalid credentials file '%s' format:" % cert_creds_file return False self.recaptcha_creds = None if recaptcha_creds["enabled"]: print "Cert. Initialize recaptcha. Recaptcha is enabled" encryptionService = CdiUtil.bean(EncryptionService) site_key = recaptcha_creds["site_key"] secret_key = recaptcha_creds["secret_key"] try: site_key = encryptionService.decrypt(site_key) except: # Ignore exception. Value is not encrypted print "Cert. Initialize recaptcha. Assuming that 'site_key' in not encrypted" try: secret_key = encryptionService.decrypt(secret_key) except: # Ignore exception. Value is not encrypted print "Cert. Initialize recaptcha. Assuming that 'secret_key' in not encrypted" self.recaptcha_creds = { 'site_key': site_key, "secret_key": secret_key } print "Cert. Initialize recaptcha. Recaptcha is configured correctly" return True else: print "Cert. Initialize recaptcha. Recaptcha is disabled" return False
def initPushNotificationService(self, configurationAttributes): print "Super-Gluu. Initialize notification services" if not configurationAttributes.containsKey("credentials_file"): return False super_gluu_creds_file = configurationAttributes.get( "credentials_file").getValue2() # Load credentials from file f = open(super_gluu_creds_file, 'r') try: creds = json.loads(f.read()) except: print "Super-Gluu. Initialize notification services. Failed to load credentials from file:", super_gluu_creds_file return False finally: f.close() try: android_creds = creds["android"]["gcm"] ios_creads = creds["ios"]["apns"] except: print "Super-Gluu. Initialize notification services. Invalid credentials file '%s' format:" % super_gluu_creds_file return False self.pushAndroidService = None self.pushAppleService = None if android_creds["enabled"]: self.pushAndroidService = Sender(android_creds["api_key"]) print "Super-Gluu. Initialize notification services. Created Android notification service" if ios_creads["enabled"]: p12_file_path = ios_creads["p12_file_path"] p12_passowrd = ios_creads["p12_password"] try: encryptionService = CdiUtil.bean(EncryptionService) p12_passowrd = encryptionService.decrypt(p12_passowrd) except: # Ignore exception. Password is not encrypted print "Super-Gluu. Initialize notification services. Assuming that 'p12_passowrd' password in not encrypted" apnsServiceBuilder = APNS.newService().withCert( p12_file_path, p12_passowrd) if ios_creads["production"]: self.pushAppleService = apnsServiceBuilder.withProductionDestination( ).build() else: self.pushAppleService = apnsServiceBuilder.withSandboxDestination( ).build() print "Super-Gluu. Initialize notification services. Created iOS notification service" enabled = self.pushAndroidService != None or self.pushAppleService != None return enabled
def getCountAuthenticationSteps(self, configurationAttributes): identity = CdiUtil.bean(Identity) sessionAttributes = identity.getSessionId().getSessionAttributes() if (sessionAttributes != None ) and sessionAttributes.containsKey("wikid_count_login_steps"): return java.lang.Integer.valueOf( sessionAttributes.get("wikid_count_login_steps")) return 2
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() 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): return True idx += 1 return False else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) 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() identity.setWorkingParameter("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 identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() sessionAttributes = identity.getSessionId().getSessionAttributes() if (sessionAttributes == None) or not sessionAttributes.containsKey("oxpush_user_uid"): 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 identity.setWorkingParameter("oxpush_pairing_uid", pairing_id) identity.setWorkingParameter("oxpush_pairing_code", pairing_process.pairingCode) identity.setWorkingParameter("oxpush_pairing_qr_image", pairing_process.pairingQrImage)
def prepareForStep(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) httpService = CdiUtil.bean(HttpService) cas_host = configurationAttributes.get("cas_host").getValue2() cas_renew_opt = StringHelper.toBoolean( configurationAttributes.get("cas_renew_opt").getValue2(), False) cas_extra_opts = None if (configurationAttributes.containsKey("cas_extra_opts")): cas_extra_opts = configurationAttributes.get( "cas_extra_opts").getValue2() if (step == 1): print "CAS2. Prepare for step 1" facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() parametersMap = HashMap() parametersMap.put( "service", httpService.constructServerUrl(request) + "/postlogin") if (cas_renew_opt): parametersMap.put("renew", "true") cas_service_request_uri = authenticationService.parametersAsString( parametersMap) cas_service_request_uri = cas_host + "/login?" + cas_service_request_uri if cas_extra_opts != None: cas_service_request_uri = cas_service_request_uri + "&" + 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
def init(self, configurationAttributes): print "Casa. init called" self.authenticators = {} self.configFileLocation = "/etc/gluu/conf/casa.json" self.uid_attr = self.getLocalPrimaryKey() custScriptService = CdiUtil.bean(CustomScriptService) scriptsList = custScriptService.findCustomScripts( Collections.singletonList(CustomScriptType.PERSON_AUTHENTICATION), "oxConfigurationProperty", "displayName", "gluuStatus") dynamicMethods = self.computeMethods(scriptsList) if len(dynamicMethods) > 0: print "Casa. init. Loading scripts for dynamic modules: %s" % dynamicMethods for acr in dynamicMethods: moduleName = self.modulePrefix + acr try: external = __import__(moduleName, globals(), locals(), ["PersonAuthentication"], -1) module = external.PersonAuthentication( self.currentTimeMillis) print "Casa. init. Got dynamic module for acr %s" % acr configAttrs = self.getConfigurationAttributes( acr, scriptsList) if acr == self.ACR_U2F: u2f_application_id = configurationAttributes.get( "u2f_app_id").getValue2() configAttrs.put( "u2f_application_id", SimpleCustomProperty("u2f_application_id", u2f_application_id)) elif acr == self.ACR_SG: client_redirect_uri = configurationAttributes.get( "supergluu_app_id").getValue2() configAttrs.put( "client_redirect_uri", SimpleCustomProperty("client_redirect_uri", client_redirect_uri)) if module.init(configAttrs): module.configAttrs = configAttrs self.authenticators[acr] = module else: print "Casa. init. Call to init in module '%s' returned False" % moduleName except: print "Casa. init. Failed to load module %s" % moduleName print "Exception: ", sys.exc_info()[1] print "Casa. init. Initialized successfully" return True
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: Error: " + str(err))
def processBasicAuthentication(self, credentials): userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) 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 None find_user_by_uid = authenticationService.getAuthenticatedUser() if find_user_by_uid == None: print "Super-Gluu. Process basic authentication. Failed to find user '%s'" % user_name return None return find_user_by_uid
def getCountAuthenticationSteps(self, configuration_attributes): print "ThumbSignIn. Inside getCountAuthenticationSteps.." identity = CdiUtil.bean(Identity) user_login_flow = identity.getWorkingParameter(USER_LOGIN_FLOW) print "ThumbSignIn. Value of user_login_flow is %s" % user_login_flow if user_login_flow == THUMBSIGNIN_AUTHENTICATION: print "ThumbSignIn. Total Authentication Steps is: 1" return 1 print "ThumbSignIn. Total Authentication Steps is: 3" return 3
def getSmtpConfig(self): ''' get SMTP config from Gluu Server return dict ''' print "Forgot Password - SMTP CONFIG:" smtpconfig = CdiUtil.bean(ConfigurationService).getConfiguration().getSmtpConfiguration() 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
def isValidAuthenticationMethod(self, usageType, configurationAttributes): print "CAS2. Rest API authenticate isValidAuthenticationMethod" if (not (configurationAttributes.containsKey("cas_validation_uri") and configurationAttributes.containsKey("cas_validation_pattern") and configurationAttributes.containsKey( "cas_validation_timeout"))): return True cas_validation_uri = configurationAttributes.get( "cas_validation_uri").getValue2() cas_validation_pattern = configurationAttributes.get( "cas_validation_pattern").getValue2() cas_validation_timeout = int( configurationAttributes.get( "cas_validation_timeout").getValue2()) * 1000 httpService = CdiUtil.bean(HttpService) http_client = httpService.getHttpsClient() http_client_params = http_client.getParams() http_client_params.setIntParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, cas_validation_timeout) try: http_service_response = httpService.executeGet( http_client, cas_validation_uri) http_response = http_service_response.getHttpResponse() except: print "CAS2. Rest API authenticate isValidAuthenticationMethod. Exception: ", sys.exc_info( )[1] return False try: if (http_response.getStatusLine().getStatusCode() != 200): print "CAS2. Rest API authenticate isValidAuthenticationMethod. Get invalid response from CAS2 server: ", str( http_response.getStatusLine().getStatusCode()) httpService.consume(http_response) return False validation_response_bytes = httpService.getResponseContent( http_response) validation_response_string = httpService.convertEntityToString( validation_response_bytes) httpService.consume(http_response) finally: http_service_response.closeConnection() if (validation_response_string == None or validation_response_string.find(cas_validation_pattern) == -1): print "CAS2. Rest API authenticate isValidAuthenticationMethod. Get invalid login page from CAS2 server:" return False return True
def validateInweboToken(self, iw_api_uri, iw_service_id, user_name, iw_token): httpService = CdiUtil.bean(HttpService) xmlService = CdiUtil.bean(XmlService) if StringHelper.isEmpty(iw_token): print "InWebo. Token verification. iw_token is empty" return False request_uri = iw_api_uri + "?action=authenticate" + "&serviceId=" + httpService.encodeUrl( iw_service_id) + "&userId=" + httpService.encodeUrl( user_name) + "&token=" + httpService.encodeUrl(iw_token) print "InWebo. Token verification. Attempting to send authentication request:", request_uri # Execute request http_response = httpService.executeGet(self.client, request_uri) # Validate response code response_validation = httpService.isResponseStastusCodeOk( http_response) if response_validation == False: print "InWebo. Token verification. Get unsuccessful response code" return False authentication_response_bytes = httpService.getResponseContent( http_response) print "InWebo. Token verification. Get response:", httpService.convertEntityToString( authentication_response_bytes) # Validate authentication response response_validation = httpService.isContentTypeXml(http_response) if response_validation == False: print "InWebo. Token verification. Get invalid response" return False # Parse XML response try: xmlDocument = xmlService.getXmlDocument( authentication_response_bytes) except Exception, err: print "InWebo. Token verification. Failed to parse XML response:", err return False
def parseProviderConfigs(self): self.registeredProviders = {} try: print "Passport. parseProviderConfigs. Adding social providers" passportDN = CdiUtil.bean( ConfigurationFactory).getLdapConfiguration().getString( "oxpassport_ConfigurationEntryDN") entryManager = CdiUtil.bean( AppInitializer).createPersistenceEntryManager() config = LdapOxPassportConfiguration() config = entryManager.find(config.getClass(), passportDN).getPassportConfigurations() if config != None: for strategy in config: idProvider = strategy.getStrategy() provider = { "emailLinkingSafe": False, "requestForEmail": False } for field in strategy.getFieldset(): for property in provider: if StringHelper.equalsIgnoreCase( field.getValue1(), property ) and StringHelper.equalsIgnoreCase( field.getValue2(), "true"): provider[property] = True if (field.getValue1() == "logo_img"): provider["logo_img"] = field.getValue2() provider["saml"] = False if not "logo_img" in provider: provider["logo_img"] = "img/%s.png" % idProvider self.registeredProviders[idProvider] = provider except: print "Passport. parseProviderConfigs. An error occurred while building the list of supported authentication providers", sys.exc_info( )[1]
def processAuditGroup(self, user, attribute, group): is_member = self.isUserMemberOfGroup(user, attribute, group) if (is_member): print "Super-Gluu. Authenticate for processAuditGroup. User '%s' member of audit group" % user.getUserId() print "Super-Gluu. Authenticate for processAuditGroup. Sending e-mail about user '%s' login to %s" % (user.getUserId(), self.audit_email) # Send e-mail to administrator user_id = user.getUserId() mailService = CdiUtil.bean(MailService) subject = "User log in: %s" % user_id body = "User log in: %s" % user_id mailService.sendMail(self.audit_email, subject, body)
def getPageForStep(self, configurationAttributes, step): identity = CdiUtil.bean(Identity) session_attributes = identity.getSessionId().getSessionAttributes() pwdcompromised = session_attributes.get("pwd_compromised") if (pwdcompromised != None): if step == 2: return "/auth/compromised/complogin.xhtml" elif step == 3: return "/auth/compromised/newpassword.xhtml" return "" else: return ""
def getCountAuthenticationSteps(self, configurationAttributes): print "ThumbSignIn. Inside getCountAuthenticationSteps.." identity = CdiUtil.bean(Identity) userLoginFlow = identity.getWorkingParameter("userLoginFlow") print "ThumbSignIn. Value of userLoginFlow is %s" % userLoginFlow if (userLoginFlow == "ThumbSignIn_Authentication"): print "ThumbSignIn. Total Authentication Steps is: 1" return 1 #If the userLoginFlow is registration, then we can handle the ThumbSignIn registration as part of the second step print "ThumbSignIn. Total Authentication Steps is: 3" return 3
def postRegistration(self, user, requestParameters, configurationAttributes): print "User registration. Post method" appConfiguration = CdiUtil.bean(AppConfiguration) hostName = appConfiguration.getApplianceUrl() externalContext = CdiUtil.bean(ExternalContext) contextPath = externalContext.getRequest().getContextPath() mailService = CdiUtil.bean(MailService) subject = "Registration confirmation" activationLink = "%s%s/confirm/registration?code=%s" % ( hostName, contextPath, self.guid) body = "<h2 style='margin-left:10%%;color: #337ab7;'>Welcome</h2><hr style='width:80%%;border: 1px solid #337ab7;'></hr><div style='text-align:center;'><p>Dear <span style='color: #337ab7;'>%s</span>,</p><p>Your Account has been created, welcome to <span style='color: #337ab7;'>%s</span>.</p><p>You are just one step way from activating your account on <span style='color: #337ab7;'>%s</span>.</p><p>Click the button and start using your account.</p></div><a class='btn' href='%s'><button style='background: #337ab7; color: white; margin-left: 30%%; border-radius: 5px; border: 0px; padding: 5px;' type='button'>Activate your account now!</button></a>" % ( user.getUid(), hostName, hostName, activationLink) print "User registration. Post method. Attempting to send e-mail to '%s' message '%s'" % ( user.getMail(), body) mailService.sendMail(user.getMail(), None, subject, body, body) return True
def validateSessionId(self, identity): session_id = CdiUtil.bean(SessionIdService).getSessionIdFromCookie() if StringHelper.isEmpty(session_id): print "OTP. Validate session id. Failed to determine session_id" return False otp_auth_method = identity.getWorkingParameter("otp_auth_method") if not otp_auth_method in ['enroll', 'authenticate']: print "OTP. Validate session id. Failed to authenticate user. otp_auth_method: '%s'" % otp_auth_method return False return True