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