Search in sources :

Example 6 with ReadOnlyException

use of org.keycloak.storage.ReadOnlyException in project keycloak by keycloak.

the class LDAPProvidersIntegrationTest method testReadonly.

@Test
public void testReadonly() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.READ_ONLY.toString());
        appRealm.updateComponent(ctx.getLdapModel());
    });
    UserRepresentation userRep = ApiUtil.findUserByUsername(testRealm(), "johnkeycloak");
    assertFederatedUserLink(userRep);
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertNotNull(user);
        try {
            user.setEmail("error@error.com");
            Assert.fail("should fail");
        } catch (ReadOnlyException e) {
        }
        try {
            user.setLastName("Berk");
            Assert.fail("should fail");
        } catch (ReadOnlyException e) {
        }
        try {
            user.setFirstName("Bilbo");
            Assert.fail("should fail");
        } catch (ReadOnlyException e) {
        }
        try {
            UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1", true);
            session.userCredentialManager().updateCredential(appRealm, user, cred);
            Assert.fail("should fail");
        } catch (ReadOnlyException e) {
        }
        Assert.assertTrue(session.users().removeUser(appRealm, user));
    });
    // Revert
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        ctx.getLdapModel().put(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString());
        appRealm.updateComponent(ctx.getLdapModel());
        Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) UserCredentialModel(org.keycloak.models.UserCredentialModel) ReadOnlyException(org.keycloak.storage.ReadOnlyException) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 7 with ReadOnlyException

use of org.keycloak.storage.ReadOnlyException in project keycloak by keycloak.

the class RoleMapperResource method deleteRealmRoleMappings.

/**
 * Delete realm-level role mappings
 *
 * @param roles
 */
@Path("realm")
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public void deleteRealmRoleMappings(List<RoleRepresentation> roles) {
    managePermission.require();
    logger.debug("deleteRealmRoleMappings");
    if (roles == null) {
        roles = roleMapper.getRealmRoleMappingsStream().peek(roleModel -> {
            auth.roles().requireMapRole(roleModel);
            roleMapper.deleteRoleMapping(roleModel);
        }).map(ModelToRepresentation::toBriefRepresentation).collect(Collectors.toList());
    } else {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = realm.getRole(role.getName());
            if (roleModel == null || !roleModel.getId().equals(role.getId())) {
                throw new NotFoundException("Role not found");
            }
            auth.roles().requireMapRole(roleModel);
            try {
                roleMapper.deleteRoleMapping(roleModel);
            } catch (ModelException | ReadOnlyException me) {
                logger.warn(me.getMessage(), me);
                throw new ErrorResponseException("invalid_request", "Could not remove user role mappings!", Response.Status.BAD_REQUEST);
            }
        }
    }
    adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).representation(roles).success();
}
Also used : ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) PathParam(javax.ws.rs.PathParam) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Path(javax.ws.rs.Path) HashMap(java.util.HashMap) RoleContainerModel(org.keycloak.models.RoleContainerModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) ClientConnection(org.keycloak.common.ClientConnection) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Predicate(java.util.function.Predicate) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) MappingsRepresentation(org.keycloak.representations.idm.MappingsRepresentation) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Stream(java.util.stream.Stream) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) ClientMappingsRepresentation(org.keycloak.representations.idm.ClientMappingsRepresentation) ModelException(org.keycloak.models.ModelException) RoleMapperModel(org.keycloak.models.RoleMapperModel) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ModelException(org.keycloak.models.ModelException) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes)

Example 8 with ReadOnlyException

use of org.keycloak.storage.ReadOnlyException in project keycloak by keycloak.

the class RoleMapperResource method addRealmRoleMappings.

/**
 * Add realm-level role mappings to the user
 *
 * @param roles Roles to add
 */
@Path("realm")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void addRealmRoleMappings(List<RoleRepresentation> roles) {
    managePermission.require();
    logger.debugv("** addRealmRoleMappings: {0}", roles);
    try {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = realm.getRole(role.getName());
            if (roleModel == null || !roleModel.getId().equals(role.getId())) {
                throw new NotFoundException("Role not found");
            }
            auth.roles().requireMapRole(roleModel);
            roleMapper.grantRole(roleModel);
        }
    } catch (ModelException | ReadOnlyException me) {
        logger.warn(me.getMessage(), me);
        throw new ErrorResponseException("invalid_request", "Could not add user role mappings!", Response.Status.BAD_REQUEST);
    }
    adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri()).representation(roles).success();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ModelException(org.keycloak.models.ModelException) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 9 with ReadOnlyException

use of org.keycloak.storage.ReadOnlyException 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)

Example 10 with ReadOnlyException

use of org.keycloak.storage.ReadOnlyException in project keycloak by keycloak.

the class AccountRestService method updateAccount.

@Path("/")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response updateAccount(UserRepresentation rep) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    event.event(EventType.UPDATE_PROFILE).client(auth.getClient()).user(auth.getUser()).detail(Details.CONTEXT, UserProfileContext.ACCOUNT.name());
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.ACCOUNT, rep.toAttributes(), auth.getUser());
    try {
        profile.update(new EventAuditingAttributeChangeListener(profile, event));
        event.success();
        return Response.noContent().build();
    } catch (ValidationException pve) {
        List<ErrorRepresentation> errors = new ArrayList<>();
        for (Error err : pve.getErrors()) {
            errors.add(new ErrorRepresentation(err.getAttribute(), err.getMessage(), validationErrorParamsToString(err.getMessageParameters(), profile.getAttributes())));
        }
        return ErrorResponse.errors(errors, pve.getStatusCode(), false);
    } catch (ReadOnlyException e) {
        return ErrorResponse.error(Messages.READ_ONLY_USER, Response.Status.BAD_REQUEST);
    }
}
Also used : ValidationException(org.keycloak.userprofile.ValidationException) UserProfile(org.keycloak.userprofile.UserProfile) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) EventAuditingAttributeChangeListener(org.keycloak.userprofile.EventAuditingAttributeChangeListener) Error(org.keycloak.userprofile.ValidationException.Error) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Aggregations

ReadOnlyException (org.keycloak.storage.ReadOnlyException)10 Consumes (javax.ws.rs.Consumes)9 POST (javax.ws.rs.POST)7 Path (javax.ws.rs.Path)7 ModelException (org.keycloak.models.ModelException)7 NotFoundException (javax.ws.rs.NotFoundException)6 ErrorResponseException (org.keycloak.services.ErrorResponseException)6 List (java.util.List)4 RoleModel (org.keycloak.models.RoleModel)4 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)4 ValidationException (org.keycloak.userprofile.ValidationException)4 ArrayList (java.util.ArrayList)3 Produces (javax.ws.rs.Produces)3 Response (javax.ws.rs.core.Response)3 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 UserModel (org.keycloak.models.UserModel)3 Function (java.util.function.Function)2 Predicate (java.util.function.Predicate)2 Collectors (java.util.stream.Collectors)2 Stream (java.util.stream.Stream)2