Search in sources :

Example 26 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class GroupsResource method addTopLevelGroup.

/**
 * create or add a top level realm groupSet or create child.  This will update the group and set the parent if it exists.  Create it and set the parent
 * if the group doesn't exist.
 *
 * @param rep
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addTopLevelGroup(GroupRepresentation rep) {
    auth.groups().requireManage();
    GroupModel child;
    Response.ResponseBuilder builder = Response.status(204);
    String groupName = rep.getName();
    if (ObjectUtil.isBlank(groupName)) {
        return ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
    }
    try {
        if (rep.getId() != null) {
            child = realm.getGroupById(rep.getId());
            if (child == null) {
                throw new NotFoundException("Could not find child by id");
            }
            realm.moveGroup(child, null);
            adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri());
        } else {
            child = realm.createGroup(groupName);
            GroupResource.updateGroup(rep, child);
            URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(child.getId()).build();
            builder.status(201).location(uri);
            rep.setId(child.getId());
            adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), child.getId());
        }
    } catch (ModelDuplicateException mde) {
        return ErrorResponse.exists("Top level group named '" + groupName + "' already exists.");
    }
    adminEvent.representation(rep).success();
    return builder.build();
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) GroupModel(org.keycloak.models.GroupModel) NotFoundException(javax.ws.rs.NotFoundException) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 27 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class IdentityProvidersResource method create.

/**
 * Create a new identity provider
 *
 * @param representation JSON body
 * @return
 */
@POST
@Path("instances")
@Consumes(MediaType.APPLICATION_JSON)
public Response create(IdentityProviderRepresentation representation) {
    this.auth.realm().requireManageIdentityProviders();
    ReservedCharValidator.validate(representation.getAlias());
    try {
        IdentityProviderModel identityProvider = RepresentationToModel.toModel(realm, representation, session);
        this.realm.addIdentityProvider(identityProvider);
        representation.setInternalId(identityProvider.getInternalId());
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), identityProvider.getAlias()).representation(StripSecretsUtils.strip(representation)).success();
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(representation.getAlias()).build()).build();
    } catch (IllegalArgumentException e) {
        String message = e.getMessage();
        if (message == null) {
            message = "Invalid request";
        }
        return ErrorResponse.error(message, BAD_REQUEST);
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Identity Provider " + representation.getAlias() + " already exists");
    }
}
Also used : ModelDuplicateException(org.keycloak.models.ModelDuplicateException) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 28 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class ProtocolMappersResource method createMapper.

/**
 * Create a mapper
 *
 * @param rep
 */
@Path("models")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
public Response createMapper(ProtocolMapperRepresentation rep) {
    managePermission.require();
    ProtocolMapperModel model = null;
    try {
        model = RepresentationToModel.toModel(rep);
        validateModel(model);
        model = client.addProtocolMapper(model);
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), model.getId()).representation(rep).success();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Protocol mapper exists with same name");
    }
    return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(model.getId()).build()).build();
}
Also used : ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 29 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class RealmsAdminResource method importRealm.

/**
 * Import a realm
 *
 * Imports a realm from a full representation of that realm.  Realm name must be unique.
 *
 * @param rep JSON representation of the realm
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response importRealm(final RealmRepresentation rep) {
    RealmManager realmManager = new RealmManager(session);
    AdminPermissions.realms(session, auth).requireCreateRealm();
    logger.debugv("importRealm: {0}", rep.getRealm());
    try {
        RealmModel realm = realmManager.importRealm(rep);
        grantPermissionsToRealmCreator(realm);
        URI location = AdminRoot.realmsUrl(session.getContext().getUri()).path(realm.getName()).build();
        logger.debugv("imported realm success, sending back: {0}", location.toString());
        return Response.created(location).build();
    } catch (ModelDuplicateException e) {
        logger.error("Conflict detected", e);
        return ErrorResponse.exists("Conflict detected. See logs for details");
    } catch (PasswordPolicyNotMetException e) {
        logger.error("Password policy not met for user " + e.getUsername(), e);
        if (session.getTransactionManager().isActive())
            session.getTransactionManager().setRollbackOnly();
        return ErrorResponse.error("Password policy not met. See logs for details", Response.Status.BAD_REQUEST);
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) RealmManager(org.keycloak.services.managers.RealmManager) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 30 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class RoleContainerResource method createRole.

/**
 * Create a new role for the realm or client
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createRole(final RoleRepresentation rep) {
    auth.roles().requireManage(roleContainer);
    if (rep.getName() == null) {
        throw new BadRequestException();
    }
    try {
        RoleModel role = roleContainer.addRole(rep.getName());
        role.setDescription(rep.getDescription());
        Map<String, List<String>> attributes = rep.getAttributes();
        if (attributes != null) {
            for (Map.Entry<String, List<String>> attr : attributes.entrySet()) {
                role.setAttribute(attr.getKey(), attr.getValue());
            }
        }
        rep.setId(role.getId());
        if (role.isClientRole()) {
            adminEvent.resource(ResourceType.CLIENT_ROLE);
        } else {
            adminEvent.resource(ResourceType.REALM_ROLE);
        }
        // Handling of nested composite roles for KEYCLOAK-12754
        if (rep.isComposite() && rep.getComposites() != null) {
            RoleRepresentation.Composites composites = rep.getComposites();
            Set<String> compositeRealmRoles = composites.getRealm();
            if (compositeRealmRoles != null && !compositeRealmRoles.isEmpty()) {
                Set<RoleModel> realmRoles = new LinkedHashSet<>();
                for (String roleName : compositeRealmRoles) {
                    RoleModel realmRole = realm.getRole(roleName);
                    if (realmRole == null) {
                        return ErrorResponse.error("Realm Role with name " + roleName + " does not exist", Response.Status.NOT_FOUND);
                    }
                    realmRoles.add(realmRole);
                }
                RoleUtils.expandCompositeRoles(realmRoles).forEach(role::addCompositeRole);
            }
            Map<String, List<String>> compositeClientRoles = composites.getClient();
            if (compositeClientRoles != null && !compositeClientRoles.isEmpty()) {
                Set<Map.Entry<String, List<String>>> entries = compositeClientRoles.entrySet();
                for (Map.Entry<String, List<String>> clientIdWithClientRoleNames : entries) {
                    String clientId = clientIdWithClientRoleNames.getKey();
                    List<String> clientRoleNames = clientIdWithClientRoleNames.getValue();
                    ClientModel client = realm.getClientByClientId(clientId);
                    if (client == null) {
                        continue;
                    }
                    Set<RoleModel> clientRoles = new LinkedHashSet<>();
                    for (String roleName : clientRoleNames) {
                        RoleModel clientRole = client.getRole(roleName);
                        if (clientRole == null) {
                            return ErrorResponse.error("Client Role with name " + roleName + " does not exist", Response.Status.NOT_FOUND);
                        }
                        clientRoles.add(clientRole);
                    }
                    RoleUtils.expandCompositeRoles(clientRoles).forEach(role::addCompositeRole);
                }
            }
        }
        adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo, role.getName()).representation(rep).success();
        return Response.created(uriInfo.getAbsolutePathBuilder().path(role.getName()).build()).build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Role with name " + rep.getName() + " already exists");
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) LinkedHashSet(java.util.LinkedHashSet) RoleModel(org.keycloak.models.RoleModel) ClientModel(org.keycloak.models.ClientModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) BadRequestException(javax.ws.rs.BadRequestException) List(java.util.List) Map(java.util.Map) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Aggregations

ModelDuplicateException (org.keycloak.models.ModelDuplicateException)42 Consumes (javax.ws.rs.Consumes)12 UserModel (org.keycloak.models.UserModel)11 POST (javax.ws.rs.POST)9 Response (javax.ws.rs.core.Response)6 NotFoundException (javax.ws.rs.NotFoundException)5 ClientModel (org.keycloak.models.ClientModel)5 RealmModel (org.keycloak.models.RealmModel)5 BadRequestException (javax.ws.rs.BadRequestException)4 PUT (javax.ws.rs.PUT)4 Path (javax.ws.rs.Path)4 ModelException (org.keycloak.models.ModelException)4 X509Certificate (java.security.cert.X509Certificate)3 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 ErrorResponseException (org.keycloak.services.ErrorResponseException)3 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)3 URI (java.net.URI)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 ClientScopeModel (org.keycloak.models.ClientScopeModel)2 ProtocolMapperModel (org.keycloak.models.ProtocolMapperModel)2