def getMappedUser(self, configurationAttributes, requestParameters, saml_response_attributes): # Convert Saml result attributes keys to lover case saml_response_normalized_attributes = HashMap() for saml_response_attribute_entry in saml_response_attributes.entrySet(): saml_response_normalized_attributes.put(StringHelper.toLowerCase(saml_response_attribute_entry.getKey()), saml_response_attribute_entry.getValue()) currentAttributesMapping = self.prepareCurrentAttributesMapping(self.attributesMapping, configurationAttributes, requestParameters) print "Asimba. Get mapped user. Using next attributes mapping '%s'" % currentAttributesMapping newUser = User() # Set custom object classes if self.userObjectClasses != None: print "Asimba. Get mapped user. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList(self.userObjectClasses) newUser.setCustomObjectClasses(self.userObjectClasses) for attributesMappingEntry in currentAttributesMapping.entrySet(): idpAttribute = attributesMappingEntry.getKey() localAttribute = attributesMappingEntry.getValue() if self.debugEnrollment: print "Asimba. Get mapped user. Trying to map '%s' into '%s'" % (idpAttribute, localAttribute) localAttributeValue = saml_response_normalized_attributes.get(idpAttribute) if localAttributeValue != None: if self.debugEnrollment: print "Asimba. Get mapped user. Setting attribute '%s' value '%s'" % (localAttribute, localAttributeValue) newUser.setAttribute(localAttribute, localAttributeValue) else: if newUser.getAttribute(localAttribute) == None: newUser.setAttribute(localAttribute, ArrayList()) return newUser
def addUser(self, externalUid, profile, userService): newUser = User() #Fill user attrs newUser.setAttribute("oxExternalUid", externalUid) self.fillUser(newUser, profile) newUser = userService.addUser(newUser, True) return newUser
def addUser(self, externalUid, profile, userService): print "Passport. Entered addUser()." print "Passport. addUser. externalUid = %s" % externalUid print "Passport. addUser. profile = %s" % profile newUser = User() #Fill user attrs newUser.setAttribute("oxExternalUid", externalUid, True) self.fillUser(newUser, profile) newUser = userService.addUser(newUser, True) return newUser
def create(self, externalProfile): externalUid = externalProfile.get("externalUid") if externalUid is not None: user = User() user.setUserId(uuid.uuid4().hex) user.setAttribute("oxExternalUid", externalUid, True) return user else: raise AccountError( "Account. Create. External Account is missing externalUid")
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 getUser(self, loginHint): print "MFA Chooser. getUser() called" identity = CdiUtil.bean(Identity) sessionAttributes = identity.getSessionId().getSessionAttributes() userService = CdiUtil.bean(UserService) pairwiseIdentifierService = CdiUtil.bean(PairwiseIdentifierService) # Normally we would fetch by pairwise ID ... however because there is no API for that we save MFA PAI in oxExternalUid loginHintDecrypted = self.decryptAES( self.aesKey, Base64Util.base64urldecodeToString(loginHint)) pairwiseId = loginHintDecrypted.split('|')[0] relyingParty = loginHintDecrypted.split('|')[1] # set APP for future reference in page customization sessionAttributes.put("relyingParty", relyingParty) # Get the user service and fetch the user externalUid = "sic-mfa:" + pairwiseId print "MFA Chooser: getUser(). Looking up user with externalUid = '%s'" % externalUid user = userService.getUserByAttribute("oxExternalUid", externalUid) if (user == None): # Create a new account print "MFA Chooser. authenticate. Creating new user with externalUid = '%s'" % ( externalUid) newUser = User() username = uuid.uuid4().hex newUser.setAttribute("uid", username) newUser.setAttribute("oxExternalUid", externalUid) user = userService.addUser(newUser, True) # add a Pairwise Subject Identifier for the OIDC Client userInum = user.getAttribute("inum") oidcClientId = sessionAttributes.get("client_id") sectorIdentifierUri = sessionAttributes.get("redirect_uri") pairwiseSubject = PairwiseIdentifier(sectorIdentifierUri, oidcClientId) pairwiseSubject.setId(pairwiseId) pairwiseSubject.setDn( pairwiseIdentifierService.getDnForPairwiseIdentifier( pairwiseSubject.getId(), userInum)) pairwiseIdentifierService.addPairwiseIdentifier( userInum, pairwiseSubject) return user
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) users = userService.getUsersBySample(userToSearch, 1) if users.size() > 0: return False return True
def getUser(self, pairwiseId): print "MFA. getUser() called" userService = CdiUtil.bean(UserService) clientService = CdiUtil.bean(ClientService) pairwiseIdentifierService = CdiUtil.bean(PairwiseIdentifierService) facesResources = CdiUtil.bean(FacesResources) # Get the user service and fetch the user # Normally we would fetch by pairwise ID ... however because there is no API for that we save MFA PAI in oxExternalUid externalUid = "sic-mfa:" + pairwiseId print "MFA: getUser(). Looking up user with externalUid = '%s'" % externalUid user = userService.getUserByAttribute("oxExternalUid", externalUid) if (user is None): # Create a new account print "MFA: getUser(). Creating new user with externalUid = '%s'" % (externalUid) newUser = User() userId = uuid.uuid4().hex newUser.setUserId(userId) newUser.setAttribute("oxExternalUid", externalUid) user = userService.addUser(newUser, True) # add a Pairwise Subject Identifier for the OIDC Client facesContext = facesResources.getFacesContext() httpRequest = facesContext.getCurrentInstance().getExternalContext().getRequest() clientId = httpRequest.getParameter("client_id") client = clientService.getClient(clientId) sectorIdentifierUri = client.getRedirectUris()[0] userInum = user.getAttribute("inum") pairwiseSubject = PairwiseIdentifier(sectorIdentifierUri, clientId) pairwiseSubject.setId(pairwiseId) pairwiseSubject.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier(pairwiseSubject.getId(), userInum)) pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseSubject) return user
def authenticate(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) mapUserDeployment = False enrollUserDeployment = False if (configurationAttributes.containsKey("gplus_deployment_type")): deploymentType = StringHelper.toLowerCase(configurationAttributes.get("gplus_deployment_type").getValue2()) if (StringHelper.equalsIgnoreCase(deploymentType, "map")): mapUserDeployment = True if (StringHelper.equalsIgnoreCase(deploymentType, "enroll")): enrollUserDeployment = True if (step == 1): print "Google+ Authenticate for step 1" gplusAuthCodeArray = requestParameters.get("gplus_auth_code") gplusAuthCode = gplusAuthCodeArray[0] # Check if user uses basic method to log in useBasicAuth = False if (StringHelper.isEmptyString(gplusAuthCode)): useBasicAuth = True # Use basic method to log in if (useBasicAuth): print "Google+ Authenticate for step 1. Basic authentication" identity.setWorkingParameter("gplus_count_login_steps", 1) credentials = identity.getCredentials() userName = credentials.getUsername() userPassword = credentials.getPassword() loggedIn = False if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)): userService = CdiUtil.bean(UserService) loggedIn = authenticationService.authenticate(userName, userPassword) if (not loggedIn): return False return True # Use Google+ method to log in print "Google+ Authenticate for step 1. gplusAuthCode:", gplusAuthCode currentClientSecrets = self.getCurrentClientSecrets(self.clientSecrets, configurationAttributes, requestParameters) if (currentClientSecrets == None): print "Google+ Authenticate for step 1. Client secrets configuration is invalid" return False print "Google+ Authenticate for step 1. Attempting to gets tokens" tokenResponse = self.getTokensByCode(self.clientSecrets, configurationAttributes, gplusAuthCode) if ((tokenResponse == None) or (tokenResponse.getIdToken() == None) or (tokenResponse.getAccessToken() == None)): print "Google+ Authenticate for step 1. Failed to get tokens" return False else: print "Google+ Authenticate for step 1. Successfully gets tokens" jwt = Jwt.parse(tokenResponse.getIdToken()) # TODO: Validate ID Token Signature gplusUserUid = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER) print "Google+ Authenticate for step 1. Found Google user ID in the ID token: '%s'" % gplusUserUid if (mapUserDeployment): # Use mapping to local IDP user print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: 'gplus:%s'" % gplusUserUid # Check if there is user with specified gplusUserUid foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid) if (foundUser == None): print "Google+ Authenticate for step 1. Failed to find user" print "Google+ Authenticate for step 1. Setting count steps to 2" identity.setWorkingParameter("gplus_count_login_steps", 2) identity.setWorkingParameter("gplus_user_uid", gplusUserUid) return True foundUserName = foundUser.getUserId() print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName userAuthenticated = authenticationService.authenticate(foundUserName) if (userAuthenticated == False): print "Google+ Authenticate for step 1. Failed to authenticate user" return False print "Google+ Authenticate for step 1. Setting count steps to 1" identity.setWorkingParameter("gplus_count_login_steps", 1) postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser) print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult return postLoginResult elif (enrollUserDeployment): # Use auto enrollment to local IDP print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: 'gplus:%s'" % gplusUserUid # Check if there is user with specified gplusUserUid foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid) if (foundUser == None): # Auto user enrollemnt print "Google+ Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" print "Google+ Authenticate for step 1. Attempting to gets user info" userInfoResponse = self.getUserInfo(currentClientSecrets, configurationAttributes, tokenResponse.getAccessToken()) if ((userInfoResponse == None) or (userInfoResponse.getClaims().size() == 0)): print "Google+ Authenticate for step 1. Failed to get user info" return False else: print "Google+ Authenticate for step 1. Successfully gets user info" gplusResponseAttributes = userInfoResponse.getClaims() # Convert Google+ user claims to lover case gplusResponseNormalizedAttributes = HashMap() for gplusResponseAttributeEntry in gplusResponseAttributes.entrySet(): gplusResponseNormalizedAttributes.put( StringHelper.toLowerCase(gplusResponseAttributeEntry.getKey()), gplusResponseAttributeEntry.getValue()) currentAttributesMapping = self.getCurrentAttributesMapping(self.attributesMapping, configurationAttributes, requestParameters) print "Google+ Authenticate for step 1. Using next attributes mapping '%s'" % currentAttributesMapping newUser = User() for attributesMappingEntry in currentAttributesMapping.entrySet(): remoteAttribute = attributesMappingEntry.getKey() localAttribute = attributesMappingEntry.getValue() localAttributeValue = gplusResponseNormalizedAttributes.get(remoteAttribute) if (localAttribute != None): newUser.setAttribute(localAttribute, localAttributeValue) if (newUser.getAttribute("sn") == None): newUser.setAttribute("sn", gplusUserUid) if (newUser.getAttribute("cn") == None): newUser.setAttribute("cn", gplusUserUid) # Add mail to oxTrustEmail so that the user's # email is available through the SCIM interface # too. if (newUser.getAttribute("oxTrustEmail") is None and newUser.getAttribute("mail") is not None): oxTrustEmail = { "value": newUser.getAttribute("mail"), "display": newUser.getAttribute("mail"), "primary": True, "operation": None, "reference": None, "type": "other" } newUser.setAttribute("oxTrustEmail", json.dumps(oxTrustEmail)) newUser.setAttribute("oxExternalUid", "gplus:" + gplusUserUid) print "Google+ Authenticate for step 1. Attempting to add user '%s' with next attributes '%s'" % (gplusUserUid, newUser.getCustomAttributes()) foundUser = userService.addUser(newUser, True) print "Google+ Authenticate for step 1. Added new user with UID: '%s'" % foundUser.getUserId() foundUserName = foundUser.getUserId() print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName userAuthenticated = authenticationService.authenticate(foundUserName) if (userAuthenticated == False): print "Google+ Authenticate for step 1. Failed to authenticate user" return False print "Google+ Authenticate for step 1. Setting count steps to 1" identity.setWorkingParameter("gplus_count_login_steps", 1) print "Google+ Authenticate for step 1. Attempting to run extension postLogin" postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser) print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult return postLoginResult else: # Check if there is user with specified gplusUserUid print "Google+ Authenticate for step 1. Attempting to find user by uid: '%s'" % gplusUserUid foundUser = userService.getUser(gplusUserUid) if (foundUser == None): print "Google+ Authenticate for step 1. Failed to find user" return False foundUserName = foundUser.getUserId() print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName userAuthenticated = authenticationService.authenticate(foundUserName) if (userAuthenticated == False): print "Google+ Authenticate for step 1. Failed to authenticate user" return False print "Google+ Authenticate for step 1. Setting count steps to 1" identity.setWorkingParameter("gplus_count_login_steps", 1) postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser) print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult return postLoginResult elif (step == 2): print "Google+ Authenticate for step 2" sessionAttributes = identity.getSessionId().getSessionAttributes() if (sessionAttributes == None) or not sessionAttributes.containsKey("gplus_user_uid"): print "Google+ Authenticate for step 2. gplus_user_uid is empty" return False gplusUserUid = sessionAttributes.get("gplus_user_uid") passed_step1 = StringHelper.isNotEmptyString(gplusUserUid) if (not passed_step1): return False identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() userName = credentials.getUsername() userPassword = credentials.getPassword() loggedIn = False if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)): loggedIn = authenticationService.authenticate(userName, userPassword) if (not loggedIn): return False # Check if there is user which has gplusUserUid # Avoid mapping Google account to more than one IDP account foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid) if (foundUser == None): # Add gplusUserUid to user one id UIDs foundUser = userService.addUserAttribute(userName, "oxExternalUid", "gplus:" + gplusUserUid) if (foundUser == None): print "Google+ Authenticate for step 2. Failed to update current user" return False postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser) print "Google+ Authenticate for step 2. postLoginResult: '%s'" % postLoginResult return postLoginResult else: foundUserName = foundUser.getUserId() print "Google+ Authenticate for step 2. foundUserName: '******'" % foundUserName if StringHelper.equals(userName, foundUserName): postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser) print "Google+ Authenticate for step 2. postLoginResult: '%s'" % postLoginResult return postLoginResult return False else: return False