Search in sources :

Example 21 with ModelDuplicateException

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);
    }
}
Also used : UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) ModelException(org.keycloak.models.ModelException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) VerificationException(org.keycloak.common.VerificationException) UserCache(org.keycloak.models.cache.UserCache) X509Certificate(java.security.cert.X509Certificate) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) BadRequestException(javax.ws.rs.BadRequestException) ParseException(java.text.ParseException) VerificationException(org.keycloak.common.VerificationException) NotFoundException(javax.ws.rs.NotFoundException) ModelException(org.keycloak.models.ModelException) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 22 with ModelDuplicateException

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");
    }
}
Also used : ModelDuplicateException(org.keycloak.models.ModelDuplicateException) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 23 with ModelDuplicateException

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"));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) RunOnServerException(org.keycloak.testsuite.runonserver.RunOnServerException) Test(org.junit.Test)

Example 24 with ModelDuplicateException

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);
}
Also used : CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject)

Example 25 with ModelDuplicateException

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);
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) ForbiddenException(org.keycloak.services.ForbiddenException) UserLoginFailureModel(org.keycloak.models.UserLoginFailureModel) UserProfile(org.keycloak.userprofile.UserProfile) ModelException(org.keycloak.models.ModelException) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) ReadOnlyException(org.keycloak.storage.ReadOnlyException) ErrorResponseException(org.keycloak.services.ErrorResponseException) WebApplicationException(javax.ws.rs.WebApplicationException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ValidationException(org.keycloak.userprofile.ValidationException) ReadOnlyException(org.keycloak.storage.ReadOnlyException) BadRequestException(javax.ws.rs.BadRequestException) NotFoundException(javax.ws.rs.NotFoundException) ForbiddenException(org.keycloak.services.ForbiddenException) EmailException(org.keycloak.email.EmailException) ModelException(org.keycloak.models.ModelException) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

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