Search in sources :

Example 6 with NotAllowedException

use of javax.ws.rs.NotAllowedException in project com-liferay-apio-architect by liferay.

the class ExceptionSupplierUtilTest method testNotAllowedWithOneComponentPathDoesNotAddSlashes.

@Test
public void testNotAllowedWithOneComponentPathDoesNotAddSlashes() {
    NotAllowedException notAllowedException = notAllowed(PUT, "a").get();
    String expected = PUT.name() + " method is not allowed for path a";
    assertThat(notAllowedException.getMessage(), is(expected));
}
Also used : NotAllowedException(javax.ws.rs.NotAllowedException) Test(org.junit.Test)

Example 7 with NotAllowedException

use of javax.ws.rs.NotAllowedException in project com-liferay-apio-architect by liferay.

the class ExceptionSupplierUtil method notAllowed.

/**
 * Returns a supplier of {@code NotAllowedException}.
 *
 * @param  method the method that isn't allowed
 * @param  path the path in which the method isn't allowed. The path's
 *         components are joined using forward slashes {@code /}
 * @return a supplier of {@code NotAllowedException}
 */
public static Supplier<NotAllowedException> notAllowed(Method method, String... path) {
    String message = method.name() + " method is not allowed for path " + String.join("/", path);
    Response response = Response.status(METHOD_NOT_ALLOWED).build();
    return () -> new NotAllowedException(message, response);
}
Also used : Response(javax.ws.rs.core.Response) NotAllowedException(javax.ws.rs.NotAllowedException)

Example 8 with NotAllowedException

use of javax.ws.rs.NotAllowedException in project openremote by openremote.

the class ManagerKeycloakIdentityProvider method createUpdateUser.

@Override
public User createUpdateUser(String realm, final User user, String passwordSecret) throws WebApplicationException {
    return getRealms(realmsResource -> {
        if (user.getUsername() == null) {
            throw new BadRequestException("Attempt to create/update user but no username provided: User=" + user);
        }
        // Force lowercase username
        user.setUsername(user.getUsername().toLowerCase(Locale.ROOT));
        boolean isUpdate = false;
        User existingUser = user.getId() != null ? getUser(realm, user.getId()) : getUserByUsername(realm, user.getUsername());
        ClientRepresentation clientRepresentation;
        UserRepresentation userRepresentation;
        if (existingUser == null && user.isServiceAccount()) {
            // Could be a service user
            userRepresentation = withClientResource(realm, user.getUsername(), realmsResource, (clientRep, clientResource) -> {
                UserRepresentation userRep = clientResource.getServiceAccountUser();
                if (userRep == null) {
                    String msg = "Attempt to update/create service user but a regular client with same client ID as this username already exists: User=" + user;
                    LOG.info(msg);
                    throw new NotAllowedException(msg);
                }
                return userRep;
            }, null);
            if (userRepresentation != null) {
                existingUser = convert(userRepresentation, User.class);
            }
        }
        if (existingUser != null && user.getId() != null && !existingUser.getId().equals(user.getId())) {
            String msg = "Attempt to update user but retrieved user ID doesn't match supplied so ignoring: User=" + user;
            LOG.info(msg);
            throw new BadRequestException(msg);
        }
        if (existingUser != null) {
            isUpdate = true;
            if (existingUser.isServiceAccount() != user.isServiceAccount()) {
                String msg = "Attempt to update user service account flag not allowed: User=" + user;
                LOG.info(msg);
                throw new NotAllowedException(msg);
            }
            if (existingUser.isServiceAccount() && !existingUser.getUsername().equals(user.getUsername())) {
                String msg = "Attempt to update username of service user not allowed: User=" + user;
                LOG.info(msg);
                throw new NotAllowedException(msg);
            }
        }
        // For service users we don't actually create the user - keycloak does that when the client is created
        if (isUpdate) {
            // User only has a subset of user representation so overlay on actual user representation
            UserResource userResource = realmsResource.realm(realm).users().get(existingUser.getId());
            userRepresentation = userResource.toRepresentation();
            userRepresentation.setFirstName(user.getFirstName());
            userRepresentation.setLastName(user.getLastName());
            userRepresentation.setEmail(user.getEmail());
            userRepresentation.setEnabled(user.getEnabled());
            userResource.update(userRepresentation);
        } else {
            if (user.isServiceAccount()) {
                // Just create client with service account and user will be generated
                clientRepresentation = new ClientRepresentation();
                clientRepresentation.setStandardFlowEnabled(false);
                clientRepresentation.setImplicitFlowEnabled(false);
                clientRepresentation.setDirectAccessGrantsEnabled(false);
                clientRepresentation.setServiceAccountsEnabled(true);
                clientRepresentation.setClientAuthenticatorType("client-secret");
                clientRepresentation.setClientId(user.getUsername());
                clientRepresentation.setSecret(passwordSecret);
                clientRepresentation = createUpdateClient(realm, clientRepresentation);
                userRepresentation = realmsResource.realm(realm).clients().get(clientRepresentation.getId()).getServiceAccountUser();
                userRepresentation.setEnabled(user.getEnabled());
                realmsResource.realm(realm).users().get(userRepresentation.getId()).update(userRepresentation);
            } else {
                userRepresentation = convert(user, UserRepresentation.class);
                RealmResource realmResource = realmsResource.realm(realm);
                Response response = realmResource.users().create(userRepresentation);
                String location = response.getHeaderString(Headers.LOCATION_STRING);
                response.close();
                if (!response.getStatusInfo().equals(Response.Status.CREATED) || TextUtil.isNullOrEmpty(location)) {
                    throw new BadRequestException("Failed to create user: User=" + user);
                }
                String[] locationArr = location.split("/");
                String userId = locationArr.length > 0 ? locationArr[locationArr.length - 1] : null;
                userRepresentation = realmResource.users().get(userId).toRepresentation();
            }
        }
        if (passwordSecret != null || (!isUpdate && user.isServiceAccount())) {
            if (user.isServiceAccount()) {
                resetSecret(realm, userRepresentation.getId(), passwordSecret);
            } else {
                Credential credential = new Credential(passwordSecret, false);
                resetPassword(realm, userRepresentation.getId(), credential);
            }
        }
        if (user.getAttributes() != null) {
            if (existingUser != null) {
                // Populate attributes for persistence event
                existingUser.setAttributes(getUserAttributes(realm, existingUser.getId()));
            }
            updateUserAttributes(realm, userRepresentation.getId(), user.getAttributes());
        }
        User updatedUser = convert(userRepresentation, User.class);
        if (updatedUser != null) {
            updatedUser.setRealm(realm);
            if (updatedUser.isServiceAccount()) {
                updatedUser.setSecret(passwordSecret);
            }
            if (existingUser != null) {
                // Push realm ID into updated user
                updatedUser.setRealmId(existingUser.getRealmId());
            }
        }
        persistenceService.publishPersistenceEvent((isUpdate ? PersistenceEvent.Cause.UPDATE : PersistenceEvent.Cause.CREATE), updatedUser, existingUser, User.getPropertyFields());
        return updatedUser;
    });
}
Also used : org.openremote.model.security(org.openremote.model.security) org.keycloak.representations.idm(org.keycloak.representations.idm) AuthContext(org.openremote.container.security.AuthContext) BiFunction(java.util.function.BiFunction) ValueUtil.convert(org.openremote.model.util.ValueUtil.convert) KeycloakIdentityProvider(org.openremote.container.security.keycloak.KeycloakIdentityProvider) ValueUtil(org.openremote.model.util.ValueUtil) NotAllowedException(javax.ws.rs.NotAllowedException) MapAccess.getString(org.openremote.container.util.MapAccess.getString) UserQuery(org.openremote.model.query.UserQuery) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) TextUtil(org.openremote.model.util.TextUtil) Path(java.nio.file.Path) WEBSERVER_ALLOWED_ORIGINS(org.openremote.container.web.WebService.WEBSERVER_ALLOWED_ORIGINS) OAuthGrant(org.openremote.model.auth.OAuthGrant) StandardOpenOption(java.nio.file.StandardOpenOption) Constants(org.openremote.model.Constants) NotNull(javax.validation.constraints.NotNull) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Container(org.openremote.model.Container) IOUtils(org.apache.commons.io.IOUtils) SslRequired(org.keycloak.common.enums.SslRequired) StringPredicate(org.openremote.model.query.filter.StringPredicate) Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) java.util(java.util) WEBSERVER_ALLOWED_ORIGINS_DEFAULT(org.openremote.container.web.WebService.WEBSERVER_ALLOWED_ORIGINS_DEFAULT) WebService(org.openremote.container.web.WebService) Supplier(java.util.function.Supplier) Level(java.util.logging.Level) TenantFilter(org.openremote.model.event.shared.TenantFilter) PersistenceService(org.openremote.container.persistence.PersistenceService) MapAccess.getBoolean(org.openremote.container.util.MapAccess.getBoolean) UserResource(org.keycloak.admin.client.resource.UserResource) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) Files(java.nio.file.Files) AssetQuery(org.openremote.model.query.AssetQuery) ConsoleAppService(org.openremote.manager.apps.ConsoleAppService) ClientEventService(org.openremote.manager.event.ClientEventService) org.keycloak.admin.client.resource(org.keycloak.admin.client.resource) Paths(java.nio.file.Paths) TimerService(org.openremote.container.timer.TimerService) Headers(io.undertow.util.Headers) InputStream(java.io.InputStream) NotAllowedException(javax.ws.rs.NotAllowedException) UserResource(org.keycloak.admin.client.resource.UserResource) MapAccess.getString(org.openremote.container.util.MapAccess.getString) Response(javax.ws.rs.core.Response) BadRequestException(javax.ws.rs.BadRequestException)

Example 9 with NotAllowedException

use of javax.ws.rs.NotAllowedException in project graylog2-server by Graylog2.

the class AuthzRolesResource method delete.

@DELETE
@Path("{roleId}")
@AuditEvent(type = AuditEventTypes.ROLE_DELETE)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("Delete a role")
public void delete(@ApiParam(name = "roleId") @PathParam("roleId") @NotBlank String roleId) {
    checkPermission(RestPermissions.ROLES_EDIT);
    final AuthzRoleDTO roleDTO = authzRolesService.get(roleId).orElseThrow(() -> new NotFoundException("Could not delete role with id: " + roleId));
    if (roleDTO.readOnly()) {
        throw new NotAllowedException("Cannot delete read only role with id: " + roleId);
    }
    authzRolesService.delete(roleId);
}
Also used : NotAllowedException(javax.ws.rs.NotAllowedException) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) AuditEvent(org.graylog2.audit.jersey.AuditEvent)

Aggregations

NotAllowedException (javax.ws.rs.NotAllowedException)9 Response (javax.ws.rs.core.Response)5 NotFoundException (javax.ws.rs.NotFoundException)4 BadRequestException (javax.ws.rs.BadRequestException)3 NotAcceptableException (javax.ws.rs.NotAcceptableException)3 NotSupportedException (javax.ws.rs.NotSupportedException)3 Test (org.junit.Test)3 ForbiddenException (javax.ws.rs.ForbiddenException)2 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)2 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)2 ServiceUnavailableException (javax.ws.rs.ServiceUnavailableException)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 ApiOperation (io.swagger.annotations.ApiOperation)1 Headers (io.undertow.util.Headers)1 InputStream (java.io.InputStream)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 StandardOpenOption (java.nio.file.StandardOpenOption)1