Java Code Examples for org.wso2.carbon.user.core.UserStoreManager#addUser()

The following examples show how to use org.wso2.carbon.user.core.UserStoreManager#addUser() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CSVUserBulkImport.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Method to handle adding users with claim values.
 *
 * @param username : The name of the importing user.
 * @param line : The line read from the CSV file.
 * @param userStore : The user store which the user should be imported to.
 * @throws UserStoreException : Throws when there is any error occurred while adding the user to user store.
 */
private void addUserWithClaims(String username, String[] line, UserStoreManager userStore)
        throws UserStoreException {
    String roleString = null;
    String[] roles = null;
    String password = line[1];
    Map<String, String> claims = new HashMap<>();
    for (int i = 2; i < line.length; i++) {
        if (StringUtils.isNotBlank(line[i])) {
            String[] claimStrings = line[i].split("=");
            if (claimStrings.length != 2) {
                throw new IllegalArgumentException("Claims and values are not in correct format");
            } else {
                String claimURI = claimStrings[0];
                String claimValue = claimStrings[1];
                if (claimURI.contains("role")) {
                    roleString = claimValue;
                } else {
                    if (!claimURI.isEmpty()) {
                        // Not trimming the claim values as we should not restrict the claim values not to have
                        // leading or trailing whitespaces.
                        claims.put(claimURI.trim(), claimValue);
                    }
                }
            }
        }
    }

    if (StringUtils.isNotBlank(roleString)) {
        roles = roleString.split(":");
    }

    userStore.addUser(username, password, roles, claims, null, true);
}
 
Example 2
Source File: CSVUserBulkImport.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void addUserWithClaims(String username, String[] line, UserStoreManager userStore)
        throws UserStoreException, UserAdminException {
    String roleString = null;
    String[] roles = null;
    String password = line[1];
    Map<String, String> claims = new HashMap<String, String>();
    for (int i = 2; i < line.length; i++) {
        if (line[i] != null && !line[i].isEmpty()) {
            String[] claimStrings = line[i].split("=");
            if (claimStrings.length != 2) {
                throw new UserAdminException("Claims and values are not in correct format");
            } else {
                if (claimStrings[0].contains("role")) {
                    roleString = claimStrings[1];
                } else {
                    claims.put(claimStrings[0], claimStrings[1]);
                }
            }

        }
    }

    if (roleString != null && !roleString.isEmpty()) {
        roles = roleString.split(":");
    }

    userStore.addUser(username, password, roles, claims, null, true);
}
 
Example 3
Source File: UserRegistrationService.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
private void addUser(String userName, String password, Map<String, String> claimList,
                     String profileName, UserRealm realm) throws IdentityException {
    UserStoreManager admin = null;
    Permission permission = null;
    try {
        // get config from tenant registry
        TenantRegistrationConfig tenantConfig = getTenantSignUpConfig(realm.getUserStoreManager().getTenantId());
        // set tenant config specific sign up domain
        if (tenantConfig != null && !"".equals(tenantConfig.getSignUpDomain())) {
            int index = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
            if (index > 0) {
                userName = tenantConfig.getSignUpDomain().toUpperCase() + UserCoreConstants.DOMAIN_SEPARATOR
                        + userName.substring(index + 1);
            } else {
                userName = tenantConfig.getSignUpDomain().toUpperCase() + UserCoreConstants.DOMAIN_SEPARATOR
                        + userName;
            }
        }

        // add user to the relevant user store

        admin = realm.getUserStoreManager();
        if (!isUserNameWithAllowedDomainName(userName, realm)) {
            throw IdentityException.error("Domain does not permit self registration");
        }
        // add user
        admin.addUser(userName, password, null, claimList, profileName);

        // after adding the user, assign specif roles
        List<String> roleNamesArr = getRoleName(userName, tenantConfig);
        if (claimList.get(SelfRegistrationConstants.SIGN_UP_ROLE_CLAIM_URI) != null) {
            // check is a user role is specified as a claim by the client, if so add it to the roles list
            if (tenantConfig != null) {
                roleNamesArr.add(tenantConfig.getSignUpDomain().toUpperCase()
                        + UserCoreConstants.DOMAIN_SEPARATOR
                        + claimList.get(SelfRegistrationConstants.SIGN_UP_ROLE_CLAIM_URI));
            } else {
                roleNamesArr.add(UserCoreConstants.INTERNAL_DOMAIN
                        + UserCoreConstants.DOMAIN_SEPARATOR
                        + claimList.get(SelfRegistrationConstants.SIGN_UP_ROLE_CLAIM_URI));
            }
        }
        String[] identityRoleNames = roleNamesArr.toArray(new String[roleNamesArr.size()]);

        for (int i = 0; i < identityRoleNames.length; i++) {
            // if this is the first time a user signs up, needs to create role
            doAddUser(i, admin, identityRoleNames, userName, permission);
        }
    } catch (UserStoreException e) {
        throw IdentityException.error("Error occurred while adding user : " + userName + ". " + e.getMessage(), e);
    }
}
 
Example 4
Source File: ExcelUserBulkImport.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public void addUserList(UserStoreManager userStore) throws UserAdminException {

        Workbook wb = this.createWorkbook();
        Sheet sheet = wb.getSheet(wb.getSheetName(0));
        userStoreDomain = config.getUserStoreDomain();

        if (sheet == null || sheet.getLastRowNum() == -1) {
            throw new UserAdminException("The first sheet is empty");
        }
        int limit = sheet.getLastRowNum();
        boolean isDuplicate = false;
        boolean fail = false;
        for (int i = 1; i < limit + 1; i++) {
            Row row = sheet.getRow(i);
            Cell cell = row.getCell(0);
            String userName = cell.getStringCellValue();

            int index;
            index = userName.indexOf(CarbonConstants.DOMAIN_SEPARATOR);
            if (index > 0) {
                String domainFreeName = userName.substring(index + 1);
                userName = UserCoreUtil.addDomainToName(domainFreeName, userStoreDomain);
            } else {
                userName = UserCoreUtil.addDomainToName(userName, userStoreDomain);
            }

            if (StringUtils.isNotBlank(userName)) {
                try {
                    if (!userStore.isExistingUser(userName)) {
                        userStore.addUser(userName, null, null, null, null, true);
                        successCount++;
                        if (log.isDebugEnabled()) {
                            log.debug("User import successful - Username : " + userName);
                        }
                    } else {
                        duplicateCount++;
                        duplicateUsers.add(userName);
                        isDuplicate = true;
                        log.error("User import unsuccessful - Username : " + userName + " - Error: Duplicate user");
                        duplicateUsers.add(userName);
                    }
                } catch (UserStoreException e) {
                    fail = true;
                    failCount++;
                    log.error("User import unsuccessful - Username : " + userName + " - Error: " +
                            e.getMessage());
                    errorUsersMap.put(userName, e.getMessage());
                }
            }
        }

        String summeryLog = super.buildBulkImportSummary();
        log.info(summeryLog);

        JSONConverter jsonConverter = new JSONConverter();
        String importedUsers = jsonConverter.xlsToJSON(sheet);
        auditLog.info(String.format(UserMgtConstants.AUDIT_LOG_FORMAT, tenantUser, UserMgtConstants.OPERATION_NAME,
                userStoreDomain, importedUsers, summeryLog));

        if (fail || isDuplicate) {
            throw new UserAdminException(String.format(UserMgtConstants.ERROR_MESSAGE, successCount, failCount,
                    duplicateCount));
        }
    }
 
Example 5
Source File: DefaultProvisioningHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(List<String> roles, String subject, Map<String, String> attributes,
                   String provisioningUserStoreId, String tenantDomain) throws FrameworkException {

    RegistryService registryService = FrameworkServiceComponent.getRegistryService();
    RealmService realmService = FrameworkServiceComponent.getRealmService();

    try {
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,
                                                                      realmService, tenantDomain);

        String userStoreDomain = getUserStoreDomain(provisioningUserStoreId, realm);

        String username = MultitenantUtils.getTenantAwareUsername(subject);

        UserStoreManager userStoreManager = getUserStoreManager(realm, userStoreDomain);

        // Remove userStoreManager domain from username if the userStoreDomain is not primary
        if (realm.getUserStoreManager().getRealmConfiguration().isPrimary()) {
            username = UserCoreUtil.removeDomainFromName(username);
        }

        String[] newRoles = new String[]{};

        if (roles != null) {
            roles = removeDomainFromNamesExcludeInternal(roles, userStoreManager.getTenantId());
            newRoles = roles.toArray(new String[roles.size()]);
        }

        if (log.isDebugEnabled()) {
            log.debug("User " + username + " contains roles : " + Arrays.toString(newRoles)
                      + " going to be provisioned");
        }

        // addingRoles = newRoles AND allExistingRoles
        Collection<String> addingRoles = getRolesToAdd(userStoreManager, newRoles);

        Map<String, String> userClaims = prepareClaimMappings(attributes);

        if (userStoreManager.isExistingUser(username)) {

            if (roles != null && !roles.isEmpty()) {
                // Update user
                Collection<String> currentRolesList = Arrays.asList(userStoreManager
                                                                            .getRoleListOfUser(username));
                // addingRoles = (newRoles AND existingRoles) - currentRolesList)
                addingRoles.removeAll(currentRolesList);

                Collection<String> deletingRoles = new ArrayList<String>();
                deletingRoles.addAll(currentRolesList);
                // deletingRoles = currentRolesList - newRoles
                deletingRoles.removeAll(Arrays.asList(newRoles));

                // Exclude Internal/everyonerole from deleting role since its cannot be deleted
                deletingRoles.remove(realm.getRealmConfiguration().getEveryOneRoleName());

                // TODO : Does it need to check this?
                // Check for case whether superadmin login
                handleFederatedUserNameEqualsToSuperAdminUserName(realm, username, userStoreManager, deletingRoles);

                updateUserWithNewRoleSet(username, userStoreManager, newRoles, addingRoles, deletingRoles);
            }

            if (!userClaims.isEmpty()) {
                userStoreManager.setUserClaimValues(username, userClaims, null);
            }

        } else {

            userStoreManager.addUser(username, generatePassword(), addingRoles.toArray(
                    new String[addingRoles.size()]), userClaims, null);

            if (log.isDebugEnabled()) {
                log.debug("Federated user: " + username
                          + " is provisioned by authentication framework with roles : "
                          + Arrays.toString(addingRoles.toArray(new String[addingRoles.size()])));
            }
        }

        PermissionUpdateUtil.updatePermissionTree(tenantId);

    } catch (org.wso2.carbon.user.api.UserStoreException | CarbonException e) {
        throw new FrameworkException("Error while provisioning user : " + subject, e);
    }
}
 
Example 6
Source File: UserRegistrationService.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void addUser(String userName, String password, Map<String, String> claimList,
                     String profileName, UserRealm realm) throws IdentityException {
    UserStoreManager admin = null;
    Permission permission = null;
    try {
        // get config from tenant registry
        TenantRegistrationConfig tenantConfig = getTenantSignUpConfig(realm.getUserStoreManager().getTenantId());
        // set tenant config specific sign up domain
        if (tenantConfig != null && !"".equals(tenantConfig.getSignUpDomain())) {
            int index = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
            if (index > 0) {
                userName = tenantConfig.getSignUpDomain().toUpperCase() + UserCoreConstants.DOMAIN_SEPARATOR
                        + userName.substring(index + 1);
            } else {
                userName = tenantConfig.getSignUpDomain().toUpperCase() + UserCoreConstants.DOMAIN_SEPARATOR
                        + userName;
            }
        }

        // add user to the relevant user store

        admin = realm.getUserStoreManager();
        if (!isUserNameWithAllowedDomainName(userName, realm)) {
            throw IdentityException.error("Domain does not permit self registration");
        }
        // add user
        admin.addUser(userName, password, null, claimList, profileName);

        // after adding the user, assign specif roles
        List<String> roleNamesArr = getRoleName(userName, tenantConfig);
        if (claimList.get(SelfRegistrationConstants.SIGN_UP_ROLE_CLAIM_URI) != null) {
            // check is a user role is specified as a claim by the client, if so add it to the roles list
            if (tenantConfig != null) {
                roleNamesArr.add(tenantConfig.getSignUpDomain().toUpperCase()
                        + UserCoreConstants.DOMAIN_SEPARATOR
                        + claimList.get(SelfRegistrationConstants.SIGN_UP_ROLE_CLAIM_URI));
            } else {
                roleNamesArr.add(UserCoreConstants.INTERNAL_DOMAIN
                        + UserCoreConstants.DOMAIN_SEPARATOR
                        + claimList.get(SelfRegistrationConstants.SIGN_UP_ROLE_CLAIM_URI));
            }
        }
        String[] identityRoleNames = roleNamesArr.toArray(new String[roleNamesArr.size()]);

        for (int i = 0; i < identityRoleNames.length; i++) {
            // if this is the first time a user signs up, needs to create role
            doAddUser(i,admin, identityRoleNames,userName,permission);
        }
    } catch (UserStoreException e) {
        throw IdentityException.error("Error occurred while adding user : " + userName + ". " + e.getMessage(), e);
    }
}