Search in sources :

Example 11 with Keycloak

use of org.keycloak.admin.client.Keycloak in project airavata by apache.

the class TenantManagementKeycloakImpl method getUsersWithRole.

@Override
public List<UserProfile> getUsersWithRole(PasswordCredential realmAdminCreds, String tenantId, String roleName) throws IamAdminServicesException {
    Keycloak client = null;
    try {
        client = TenantManagementKeycloakImpl.getClient(ServerSettings.getIamServerUrl(), tenantId, realmAdminCreds);
        // FIXME: this only searches through the most recent 100 users for the given role (assuming there are no more than 10,000 users in the gateway)
        int totalUserCount = client.realm(tenantId).users().count();
        logger.debug("getUsersWithRole: totalUserCount=" + totalUserCount);
        // Load all users in batches
        List<UserRepresentation> allUsers = new ArrayList<>();
        int userBatchSize = 100;
        for (int start = 0; start < totalUserCount; start = start + userBatchSize) {
            logger.debug("getUsersWithRole: fetching " + userBatchSize + " users...");
            allUsers.addAll(client.realm(tenantId).users().search(null, null, null, null, start, userBatchSize));
        }
        logger.debug("getUsersWithRole: all users count=" + allUsers.size());
        allUsers.sort((a, b) -> a.getCreatedTimestamp() - b.getCreatedTimestamp() > 0 ? -1 : 1);
        // The 100 most recently created users
        List<UserRepresentation> mostRecentUsers = allUsers.subList(0, Math.min(allUsers.size(), 100));
        logger.debug("getUsersWithRole: most recent users count=" + mostRecentUsers.size());
        List<UserProfile> usersWithRole = new ArrayList<>();
        for (UserRepresentation user : mostRecentUsers) {
            UserResource userResource = client.realm(tenantId).users().get(user.getId());
            List<RoleRepresentation> roleRepresentations = userResource.roles().realmLevel().listAll();
            for (RoleRepresentation roleRepresentation : roleRepresentations) {
                if (roleRepresentation.getName().equals(roleName)) {
                    usersWithRole.add(convertUserRepresentationToUserProfile(user, tenantId));
                    break;
                }
            }
        }
        logger.debug("getUsersWithRole: most recent users with role count=" + usersWithRole.size());
        return usersWithRole;
    } catch (ApplicationSettingsException ex) {
        logger.error("Error getting values from property file, reason: " + ex.getMessage(), ex);
        IamAdminServicesException exception = new IamAdminServicesException();
        exception.setMessage("Error getting values from property file, reason " + ex.getMessage());
        throw exception;
    } finally {
        if (client != null) {
            logger.debug("getUsersWithRole: closing client...");
            client.close();
            logger.debug("getUsersWithRole: client closed");
        }
    }
}
Also used : ApplicationSettingsException(org.apache.airavata.common.exception.ApplicationSettingsException) UserProfile(org.apache.airavata.model.user.UserProfile) IamAdminServicesException(org.apache.airavata.service.profile.iam.admin.services.cpi.exception.IamAdminServicesException) ArrayList(java.util.ArrayList) UserResource(org.keycloak.admin.client.resource.UserResource) Keycloak(org.keycloak.admin.client.Keycloak)

Example 12 with Keycloak

use of org.keycloak.admin.client.Keycloak in project airavata by apache.

the class KeycloakIdentityServerClient method migrateUserStore.

void migrateUserStore(List<UserProfileDAO> userProfiles, String targetRealm, String tempPassword, Map<String, String> roleConversionMap) {
    Map<String, RoleRepresentation> allRealmRoles = getRealmRoleNameMap(targetRealm);
    for (UserProfileDAO userProfile : userProfiles) {
        UserRepresentation user = new UserRepresentation();
        user.setUsername(userProfile.getUserName());
        user.setFirstName(userProfile.getFirstName());
        user.setLastName(userProfile.getLastName());
        user.setEmail(userProfile.getEmail());
        user.setEmailVerified(true);
        user.setEnabled(true);
        List<String> requiredActionList = new ArrayList<>();
        requiredActionList.add("UPDATE_PASSWORD");
        user.setRequiredActions(requiredActionList);
        Response httpResponse = this.client.realm(targetRealm).users().create(user);
        System.out.println(httpResponse.getStatus());
        if (httpResponse.getStatus() == 201) {
            // HTTP code for record creation: HTTP 201
            List<UserRepresentation> retrieveCreatedUserList = this.client.realm(targetRealm).users().search(user.getUsername(), user.getFirstName(), user.getLastName(), user.getEmail(), 0, 1);
            UserResource retirievedUser = this.client.realm(targetRealm).users().get(retrieveCreatedUserList.get(0).getId());
            // Add user to realm roles
            List<RoleRepresentation> userRealmRoles = userProfile.getRoles().stream().filter(r -> roleConversionMap.containsKey(r)).map(r -> roleConversionMap.get(r)).map(r -> allRealmRoles.get(r)).collect(Collectors.toList());
            retirievedUser.roles().realmLevel().add(userRealmRoles);
            CredentialRepresentation credential = new CredentialRepresentation();
            credential.setType(CredentialRepresentation.PASSWORD);
            credential.setValue(tempPassword);
            credential.setTemporary(true);
            retirievedUser.resetPassword(credential);
            System.out.println("User profile for user " + userProfile.getUserName() + " successfully migrated");
        } else {
            String response = httpResponse.readEntity(String.class);
            System.err.println("Failed to add user [" + userProfile.getUserName() + "] to Keycloak");
            System.err.println("Response: " + response);
        }
        if (httpResponse != null) {
            httpResponse.close();
        }
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) IOException(java.io.IOException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) Collectors(java.util.stream.Collectors) Keycloak(org.keycloak.admin.client.Keycloak) ArrayList(java.util.ArrayList) List(java.util.List) Response(javax.ws.rs.core.Response) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) Map(java.util.Map) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) KeycloakBuilder(org.keycloak.admin.client.KeycloakBuilder) UserResource(org.keycloak.admin.client.resource.UserResource) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ArrayList(java.util.ArrayList) UserResource(org.keycloak.admin.client.resource.UserResource) Response(javax.ws.rs.core.Response) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Aggregations

Keycloak (org.keycloak.admin.client.Keycloak)12 ApplicationSettingsException (org.apache.airavata.common.exception.ApplicationSettingsException)11 IamAdminServicesException (org.apache.airavata.service.profile.iam.admin.services.cpi.exception.IamAdminServicesException)11 UserResource (org.keycloak.admin.client.resource.UserResource)9 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)4 Response (javax.ws.rs.core.Response)4 RoleResource (org.keycloak.admin.client.resource.RoleResource)3 UserProfile (org.apache.airavata.model.user.UserProfile)2 FileInputStream (java.io.FileInputStream)1 KeyStore (java.security.KeyStore)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1 ResteasyClient (org.jboss.resteasy.client.jaxrs.ResteasyClient)1 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)1 KeycloakBuilder (org.keycloak.admin.client.KeycloakBuilder)1 CredentialRepresentation (org.keycloak.representations.idm.CredentialRepresentation)1 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)1 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)1