Search in sources :

Example 16 with ModelDuplicateException

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

the class MapScopeStore method create.

@Override
public Scope create(String id, String name, ResourceServer resourceServer) {
    LOG.tracef("create(%s, %s, %s)%s", id, name, resourceServer, getShortStackTrace());
    // @UniqueConstraint(columnNames = {"NAME", "RESOURCE_SERVER_ID"})
    DefaultModelCriteria<Scope> mcb = forResourceServer(resourceServer.getId()).compare(SearchableFields.NAME, Operator.EQ, name);
    if (tx.getCount(withCriteria(mcb)) > 0) {
        throw new ModelDuplicateException("Scope with name '" + name + "' for " + resourceServer.getId() + " already exists");
    }
    MapScopeEntity entity = new MapScopeEntityImpl();
    entity.setId(id);
    entity.setName(name);
    entity.setResourceServerId(resourceServer.getId());
    entity = tx.create(entity);
    return entityToAdapter(entity);
}
Also used : MapScopeEntity(org.keycloak.models.map.authorization.entity.MapScopeEntity) Scope(org.keycloak.authorization.model.Scope) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) MapScopeEntityImpl(org.keycloak.models.map.authorization.entity.MapScopeEntityImpl)

Example 17 with ModelDuplicateException

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

the class MapClientProvider method addClient.

@Override
public ClientModel addClient(RealmModel realm, String id, String clientId) {
    LOG.tracef("addClient(%s, %s, %s)%s", realm, id, clientId, getShortStackTrace());
    if (id != null && tx.read(id) != null) {
        throw new ModelDuplicateException("Client with same id exists: " + id);
    }
    if (clientId != null && getClientByClientId(realm, clientId) != null) {
        throw new ModelDuplicateException("Client with same clientId in realm " + realm.getName() + " exists: " + clientId);
    }
    MapClientEntity entity = new MapClientEntityImpl();
    entity.setId(id);
    entity.setRealmId(realm.getId());
    entity.setClientId(clientId);
    entity.setEnabled(true);
    entity.setStandardFlowEnabled(true);
    entity = tx.create(entity);
    if (clientId == null) {
        clientId = entity.getId();
        entity.setClientId(clientId);
    }
    final ClientModel resource = entityToAdapterFunc(realm).apply(entity);
    // TODO: Sending an event should be extracted to store layer
    session.getKeycloakSessionFactory().publish((ClientModel.ClientCreationEvent) () -> resource);
    // This is actualy strange contract - it should be the store code to call updateClient
    resource.updateClient();
    return resource;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException)

Example 18 with ModelDuplicateException

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

the class KeycloakApplication method importAddUser.

public void importAddUser() {
    String configDir = System.getProperty("jboss.server.config.dir");
    if (configDir != null) {
        File addUserFile = new File(configDir + File.separator + "keycloak-add-user.json");
        if (addUserFile.isFile()) {
            ServicesLogger.LOGGER.imprtingUsersFrom(addUserFile);
            List<RealmRepresentation> realms;
            try {
                realms = JsonSerialization.readValue(new FileInputStream(addUserFile), new TypeReference<List<RealmRepresentation>>() {
                });
            } catch (IOException e) {
                ServicesLogger.LOGGER.failedToLoadUsers(e);
                return;
            }
            for (RealmRepresentation realmRep : realms) {
                for (UserRepresentation userRep : realmRep.getUsers()) {
                    KeycloakSession session = sessionFactory.create();
                    try {
                        session.getTransactionManager().begin();
                        RealmModel realm = session.realms().getRealmByName(realmRep.getRealm());
                        if (realm == null) {
                            ServicesLogger.LOGGER.addUserFailedRealmNotFound(userRep.getUsername(), realmRep.getRealm());
                        }
                        UserProvider users = session.users();
                        if (users.getUserByUsername(realm, userRep.getUsername()) != null) {
                            ServicesLogger.LOGGER.notCreatingExistingUser(userRep.getUsername());
                        } else {
                            UserModel user = users.addUser(realm, userRep.getUsername());
                            user.setEnabled(userRep.isEnabled());
                            RepresentationToModel.createCredentials(userRep, session, realm, user, false);
                            RepresentationToModel.createRoleMappings(userRep, user, realm);
                            ServicesLogger.LOGGER.addUserSuccess(userRep.getUsername(), realmRep.getRealm());
                        }
                        session.getTransactionManager().commit();
                    } catch (ModelDuplicateException e) {
                        session.getTransactionManager().rollback();
                        ServicesLogger.LOGGER.addUserFailedUserExists(userRep.getUsername(), realmRep.getRealm());
                    } catch (Throwable t) {
                        session.getTransactionManager().rollback();
                        ServicesLogger.LOGGER.addUserFailed(t, userRep.getUsername(), realmRep.getRealm());
                    } finally {
                        session.close();
                    }
                }
            }
            if (!addUserFile.delete()) {
                ServicesLogger.LOGGER.failedToDeleteFile(addUserFile.getAbsolutePath());
            }
        }
    }
}
Also used : RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserProvider(org.keycloak.models.UserProvider) KeycloakSession(org.keycloak.models.KeycloakSession) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) TypeReference(com.fasterxml.jackson.core.type.TypeReference) File(java.io.File) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 19 with ModelDuplicateException

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

the class ClientResource method update.

/**
 * Update the client
 * @param rep
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response update(final ClientRepresentation rep) {
    auth.clients().requireConfigure(client);
    try {
        session.clientPolicy().triggerOnEvent(new AdminClientUpdateContext(rep, client, auth.adminAuth()));
        updateClientFromRep(rep, client, session);
        ValidationUtil.validateClient(session, client, false, r -> {
            session.getTransactionManager().setRollbackOnly();
            throw new ErrorResponseException(Errors.INVALID_INPUT, r.getAllLocalizedErrorsAsString(AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale())), Response.Status.BAD_REQUEST);
        });
        session.clientPolicy().triggerOnEvent(new AdminClientUpdatedContext(rep, client, auth.adminAuth()));
        adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();
        return Response.noContent().build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Client already exists");
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : AdminClientUpdateContext(org.keycloak.services.clientpolicy.context.AdminClientUpdateContext) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException) AdminClientUpdatedContext(org.keycloak.services.clientpolicy.context.AdminClientUpdatedContext) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 20 with ModelDuplicateException

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

the class ClientsResource method createClient.

/**
 * Create a new client
 *
 * Client's client_id must be unique!
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createClient(final ClientRepresentation rep) {
    auth.clients().requireManage();
    try {
        session.clientPolicy().triggerOnEvent(new AdminClientRegisterContext(rep, auth.adminAuth()));
        ClientModel clientModel = ClientManager.createClient(session, realm, rep);
        if (TRUE.equals(rep.isServiceAccountsEnabled())) {
            UserModel serviceAccount = session.users().getServiceAccount(clientModel);
            if (serviceAccount == null) {
                new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
            }
        }
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), clientModel.getId()).representation(rep).success();
        if (Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION) && TRUE.equals(rep.getAuthorizationServicesEnabled())) {
            AuthorizationService authorizationService = getAuthorizationService(clientModel);
            authorizationService.enable(true);
            ResourceServerRepresentation authorizationSettings = rep.getAuthorizationSettings();
            if (authorizationSettings != null) {
                authorizationService.resourceServer().importSettings(authorizationSettings);
            }
        }
        ValidationUtil.validateClient(session, clientModel, true, r -> {
            session.getTransactionManager().setRollbackOnly();
            throw new ErrorResponseException(Errors.INVALID_INPUT, r.getAllLocalizedErrorsAsString(AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale())), Response.Status.BAD_REQUEST);
        });
        session.clientPolicy().triggerOnEvent(new AdminClientRegisteredContext(clientModel, auth.adminAuth()));
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(clientModel.getId()).build()).build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Client " + rep.getClientId() + " already exists");
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) AdminClientRegisteredContext(org.keycloak.services.clientpolicy.context.AdminClientRegisteredContext) AuthorizationService(org.keycloak.authorization.admin.AuthorizationService) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) ClientManager(org.keycloak.services.managers.ClientManager) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException) RealmManager(org.keycloak.services.managers.RealmManager) AdminClientRegisterContext(org.keycloak.services.clientpolicy.context.AdminClientRegisterContext) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) 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