Search in sources :

Example 61 with ModelException

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

the class UserResource method removeMembership.

@DELETE
@Path("groups/{groupId}")
@NoCache
public void removeMembership(@PathParam("groupId") String groupId) {
    auth.users().requireManageGroupMembership(user);
    GroupModel group = session.groups().getGroupById(realm, groupId);
    if (group == null) {
        throw new NotFoundException("Group not found");
    }
    auth.groups().requireManageMembership(group);
    try {
        if (user.isMemberOf(group)) {
            user.leaveGroup(group);
            adminEvent.operation(OperationType.DELETE).resource(ResourceType.GROUP_MEMBERSHIP).representation(ModelToRepresentation.toRepresentation(group, true)).resourcePath(session.getContext().getUri()).success();
        }
    } catch (ModelException me) {
        Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale());
        throw new ErrorResponseException(me.getMessage(), MessageFormat.format(messages.getProperty(me.getMessage(), me.getMessage()), me.getParameters()), Status.BAD_REQUEST);
    }
}
Also used : ModelException(org.keycloak.models.ModelException) GroupModel(org.keycloak.models.GroupModel) NotFoundException(javax.ws.rs.NotFoundException) ErrorResponseException(org.keycloak.services.ErrorResponseException) Properties(java.util.Properties) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 62 with ModelException

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

the class LDAPRoleMappingsTest method test02_readOnlyRoleMappings.

@Test
public void test02_readOnlyRoleMappings() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.READ_ONLY);
        UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
        RoleModel realmRole1 = appRealm.getRole("realmRole1");
        RoleModel realmRole2 = appRealm.getRole("realmRole2");
        RoleModel realmRole3 = appRealm.getRole("realmRole3");
        if (realmRole3 == null) {
            realmRole3 = appRealm.addRole("realmRole3");
        }
        // Add some role mappings directly into LDAP
        ComponentModel roleMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "realmRolesMapper");
        LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
        RoleLDAPStorageMapper roleMapper = LDAPTestUtils.getRoleMapper(roleMapperModel, ldapProvider, appRealm);
        LDAPObject maryLdap = ldapProvider.loadLDAPUserByUsername(appRealm, "marykeycloak");
        roleMapper.addRoleMappingInLDAP("realmRole1", maryLdap);
        roleMapper.addRoleMappingInLDAP("realmRole2", maryLdap);
        // Add some role to model
        mary.grantRole(realmRole3);
        // Assert that mary has both LDAP and DB mapped roles
        Set<RoleModel> maryRoles = mary.getRealmRoleMappingsStream().collect(Collectors.toSet());
        Assert.assertTrue(maryRoles.contains(realmRole1));
        Assert.assertTrue(maryRoles.contains(realmRole2));
        Assert.assertTrue(maryRoles.contains(realmRole3));
        // Assert that access through DB will have just DB mapped role
        UserModel maryDB = session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak");
        Set<RoleModel> maryDBRoles = maryDB.getRealmRoleMappingsStream().collect(Collectors.toSet());
        Assert.assertFalse(maryDBRoles.contains(realmRole1));
        Assert.assertFalse(maryDBRoles.contains(realmRole2));
        Assert.assertTrue(maryDBRoles.contains(realmRole3));
        mary.deleteRoleMapping(realmRole3);
        try {
            mary.deleteRoleMapping(realmRole1);
            Assert.fail("It wasn't expected to successfully delete LDAP role mappings in READ_ONLY mode");
        } catch (ModelException expected) {
        }
        // Delete role mappings directly in LDAP
        deleteRoleMappingsInLDAP(roleMapper, maryLdap, "realmRole1");
        deleteRoleMappingsInLDAP(roleMapper, maryLdap, "realmRole2");
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
        // Assert role mappings is not available
        Set<RoleModel> maryRoles = mary.getRealmRoleMappingsStream().collect(Collectors.toSet());
        Assert.assertFalse(maryRoles.contains(appRealm.getRole("realmRole1")));
        Assert.assertFalse(maryRoles.contains(appRealm.getRole("realmRole2")));
        Assert.assertFalse(maryRoles.contains(appRealm.getRole("realmRole3")));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ModelException(org.keycloak.models.ModelException) ComponentModel(org.keycloak.component.ComponentModel) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) RoleModel(org.keycloak.models.RoleModel) RoleLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.role.RoleLDAPStorageMapper) Test(org.junit.Test)

Example 63 with ModelException

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

the class JPAResourceServerStore method create.

@Override
public ResourceServer create(ClientModel client) {
    String clientId = client.getId();
    if (!StorageId.isLocalStorage(clientId)) {
        throw new ModelException("Creating resource server from federated ClientModel not supported");
    }
    ResourceServerEntity entity = new ResourceServerEntity();
    entity.setId(clientId);
    this.entityManager.persist(entity);
    return new ResourceServerAdapter(entity, entityManager, provider.getStoreFactory());
}
Also used : ResourceServerEntity(org.keycloak.authorization.jpa.entities.ResourceServerEntity) ModelException(org.keycloak.models.ModelException)

Example 64 with ModelException

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

the class PasswordCredentialProvider method createCredential.

public boolean createCredential(RealmModel realm, UserModel user, String password) {
    PasswordPolicy policy = realm.getPasswordPolicy();
    PolicyError error = session.getProvider(PasswordPolicyManagerProvider.class).validate(realm, user, password);
    if (error != null)
        throw new ModelException(error.getMessage(), error.getParameters());
    PasswordHashProvider hash = getHashProvider(policy);
    if (hash == null) {
        return false;
    }
    PasswordCredentialModel credentialModel = hash.encodedCredential(password, policy.getHashIterations());
    credentialModel.setCreatedDate(Time.currentTimeMillis());
    createCredential(realm, user, credentialModel);
    return true;
}
Also used : ModelException(org.keycloak.models.ModelException) PasswordPolicyManagerProvider(org.keycloak.policy.PasswordPolicyManagerProvider) PasswordPolicy(org.keycloak.models.PasswordPolicy) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) PolicyError(org.keycloak.policy.PolicyError) PasswordHashProvider(org.keycloak.credential.hash.PasswordHashProvider)

Example 65 with ModelException

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

the class UserStorageManager method deleteInvalidUser.

protected void deleteInvalidUser(final RealmModel realm, final UserModel user) {
    String userId = user.getId();
    String userName = user.getUsername();
    UserCache userCache = session.userCache();
    if (userCache != null) {
        userCache.evict(realm, user);
    }
    // This needs to be running in separate transaction because removing the user may end up with throwing
    // PessimisticLockException which also rollbacks Jpa transaction, hence when it is running in current transaction
    // it will become not usable for all consequent jpa calls. It will end up with Transaction is in rolled back
    // state error
    runJobInTransaction(session.getKeycloakSessionFactory(), session -> {
        RealmModel realmModel = session.realms().getRealm(realm.getId());
        if (realmModel == null)
            return;
        UserModel deletedUser = session.userLocalStorage().getUserById(realmModel, userId);
        if (deletedUser != null) {
            try {
                new UserManager(session).removeUser(realmModel, deletedUser, session.userLocalStorage());
                logger.debugf("Removed invalid user '%s'", userName);
            } catch (ModelException ex) {
                // Ignore exception, possible cause may be concurrent deleteInvalidUser calls which means
                // ModelException exception may be ignored because users will be removed with next call or is
                // already removed
                logger.debugf(ex, "ModelException thrown during deleteInvalidUser with username '%s'", userName);
            }
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) ModelException(org.keycloak.models.ModelException) UserManager(org.keycloak.models.UserManager) OnUserCache(org.keycloak.models.cache.OnUserCache) UserCache(org.keycloak.models.cache.UserCache)

Aggregations

ModelException (org.keycloak.models.ModelException)74 RealmModel (org.keycloak.models.RealmModel)20 NamingException (javax.naming.NamingException)13 UserModel (org.keycloak.models.UserModel)13 ClientModel (org.keycloak.models.ClientModel)11 ComponentModel (org.keycloak.component.ComponentModel)10 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)10 IOException (java.io.IOException)9 Consumes (javax.ws.rs.Consumes)9 NotFoundException (javax.ws.rs.NotFoundException)8 BasicAttribute (javax.naming.directory.BasicAttribute)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 RoleModel (org.keycloak.models.RoleModel)7 ErrorResponseException (org.keycloak.services.ErrorResponseException)7 ReadOnlyException (org.keycloak.storage.ReadOnlyException)7 POST (javax.ws.rs.POST)6 Path (javax.ws.rs.Path)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 AttributeInUseException (javax.naming.directory.AttributeInUseException)5