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);
}
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;
}
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());
}
}
}
}
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);
}
}
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);
}
}
Aggregations