use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class RealmAdminResource method updateRealm.
/**
* Update the top-level information of the realm
*
* Any user, roles or client information in the representation
* will be ignored. This will only update top-level attributes of the realm.
*
* @param rep
* @return
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateRealm(final RealmRepresentation rep) {
auth.realm().requireManageRealm();
logger.debug("updating realm: " + realm.getName());
if (Config.getAdminRealm().equals(realm.getName()) && (rep.getRealm() != null && !rep.getRealm().equals(Config.getAdminRealm()))) {
return ErrorResponse.error("Can't rename master realm", Status.BAD_REQUEST);
}
ReservedCharValidator.validate(rep.getRealm());
ReservedCharValidator.validateLocales(rep.getSupportedLocales());
try {
if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getPrivateKey() != null && rep.getPublicKey() != null)) {
try {
KeyPairVerifier.verify(rep.getPrivateKey(), rep.getPublicKey());
} catch (VerificationException e) {
return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
}
}
if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getCertificate() != null)) {
try {
X509Certificate cert = PemUtils.decodeCertificate(rep.getCertificate());
if (cert == null) {
return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
}
} catch (Exception e) {
return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
}
}
boolean wasDuplicateEmailsAllowed = realm.isDuplicateEmailsAllowed();
RepresentationToModel.updateRealm(rep, realm, session);
// Refresh periodic sync tasks for configured federationProviders
UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
realm.getUserStorageProvidersStream().forEachOrdered(fedProvider -> usersSyncManager.notifyToRefreshPeriodicSync(session, realm, fedProvider, false));
// This populates the map in DefaultKeycloakContext to be used when treating the event
session.getContext().getUri();
adminEvent.operation(OperationType.UPDATE).representation(StripSecretsUtils.strip(rep)).success();
if (rep.isDuplicateEmailsAllowed() != null && rep.isDuplicateEmailsAllowed() != wasDuplicateEmailsAllowed) {
UserCache cache = session.getProvider(UserCache.class);
if (cache != null)
cache.clear();
}
return Response.noContent().build();
} catch (ModelDuplicateException e) {
return ErrorResponse.exists("Realm with same name exists");
} catch (ModelException e) {
return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ErrorResponse.error("Failed to update realm", Response.Status.INTERNAL_SERVER_ERROR);
}
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class RoleContainerResource method updateRole.
/**
* Update a role by name
*
* @param roleName role's name (not id!)
* @param rep
* @return
*/
@Path("{role-name}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateRole(@PathParam("role-name") final String roleName, final RoleRepresentation rep) {
auth.roles().requireManage(roleContainer);
RoleModel role = roleContainer.getRole(roleName);
if (role == null) {
throw new NotFoundException("Could not find role");
}
try {
updateRole(rep, role);
if (role.isClientRole()) {
adminEvent.resource(ResourceType.CLIENT_ROLE);
} else {
adminEvent.resource(ResourceType.REALM_ROLE);
}
adminEvent.operation(OperationType.UPDATE).resourcePath(uriInfo).representation(rep).success();
return Response.noContent().build();
} catch (ModelDuplicateException e) {
return ErrorResponse.exists("Role with name " + rep.getName() + " already exists");
}
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class LdapUsernameAttributeTest method testUsernameChangeAlreadyExists.
@Test
public void testUsernameChangeAlreadyExists() {
// create a user johndow and johndow2
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
UserModel john = session.users().addUser(appRealm, "johndow");
john.setEmail("johndow@email.cz");
john.setFirstName("johndow");
john.setLastName("johndow");
UserModel john2 = session.users().addUser(appRealm, "johndow2");
john.setEmail("johndow2@email.cz");
john.setFirstName("johndow2");
john.setLastName("johndow2");
});
// check they are there
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
UserModel john = session.users().getUserByUsername(appRealm, "johndow");
Assert.assertNotNull(john);
Assert.assertNotNull(john.getFederationLink());
UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2");
Assert.assertNotNull(john2);
Assert.assertNotNull(john2.getFederationLink());
});
// rename johndow to johndow2 => it should fail
try {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
UserModel john = session.users().getUserByUsername(appRealm, "johndow");
john.setUsername("johndow2");
});
Assert.assertFalse("Model exception is expected here, so it should not reach this point", true);
} catch (RunOnServerException e) {
Assert.assertTrue("Model exception is expected here but another error found", e.getCause() instanceof ModelDuplicateException);
Assert.assertEquals(UserModel.USERNAME, ((ModelDuplicateException) e.getCause()).getDuplicateFieldName());
}
// remove both users
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
UserModel john = session.users().getUserByUsername(appRealm, "johndow");
Assert.assertNotNull(john);
UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2");
Assert.assertNotNull(john2);
session.users().removeUser(appRealm, john);
session.users().removeUser(appRealm, john2);
Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow"));
Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow2"));
});
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class LDAPStorageProvider method getUserByEmail.
@Override
public UserModel getUserByEmail(RealmModel realm, String email) {
LDAPObject ldapUser = queryByEmail(realm, email);
if (ldapUser == null) {
return null;
}
// Check here if user already exists
String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
UserModel user = session.userLocalStorage().getUserByUsername(realm, ldapUsername);
if (user != null) {
LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
// If email attribute mapper is set to "Always Read Value From LDAP" the user may be in Keycloak DB with an old email address
if (ldapUser.getUuid().equals(user.getFirstAttribute(LDAPConstants.LDAP_ID))) {
return proxy(realm, user, ldapUser, false);
}
throw new ModelDuplicateException("User with username '" + ldapUsername + "' already exists in Keycloak. It conflicts with LDAP user with email '" + email + "'");
}
return importUserFromLDAP(session, realm, ldapUser);
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class UserResource method updateUser.
/**
* Update the user
*
* @param rep
* @return
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateUser(final UserRepresentation rep) {
auth.users().requireManage(user);
try {
boolean wasPermanentlyLockedOut = false;
if (rep.isEnabled() != null && rep.isEnabled()) {
UserLoginFailureModel failureModel = session.loginFailures().getUserLoginFailure(realm, user.getId());
if (failureModel != null) {
failureModel.clearFailures();
}
wasPermanentlyLockedOut = session.getProvider(BruteForceProtector.class).isPermanentlyLockedOut(session, realm, user);
}
UserProfile profile = session.getProvider(UserProfileProvider.class).create(USER_API, rep.toAttributes(), user);
Response response = validateUserProfile(profile, user, session);
if (response != null) {
return response;
}
profile.update(rep.getAttributes() != null);
updateUserFromRep(profile, user, rep, session, true);
RepresentationToModel.createCredentials(rep, session, realm, user, true);
// we need to do it here as the attributes would be overwritten by what is in the rep
if (wasPermanentlyLockedOut) {
session.getProvider(BruteForceProtector.class).cleanUpPermanentLockout(session, realm, user);
}
adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();
if (session.getTransactionManager().isActive()) {
session.getTransactionManager().commit();
}
return Response.noContent().build();
} catch (ModelDuplicateException e) {
return ErrorResponse.exists("User exists with same username or email");
} catch (ReadOnlyException re) {
return ErrorResponse.error("User is read only!", Status.BAD_REQUEST);
} catch (ModelException me) {
logger.warn("Could not update user!", me);
return ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
} catch (ForbiddenException fe) {
throw fe;
} catch (Exception me) {
// JPA
// may be committed by JTA which can't
logger.warn("Could not update user!", me);
return ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
}
}
Aggregations