parent
5aafc99673
commit
0d5363d0d5
36 changed files with 220 additions and 186 deletions
|
@ -77,7 +77,7 @@ public class LdapServerCapabilitiesResource {
|
|||
Set<LDAPCapabilityRepresentation> ldapCapabilities = LDAPServerCapabilitiesManager.queryServerCapabilities(config, session, realm);
|
||||
return Response.ok().entity(ldapCapabilities).build();
|
||||
} catch (Exception e) {
|
||||
return ErrorResponse.error("ldapServerCapabilities error", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("ldapServerCapabilities error", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -72,8 +72,10 @@ public class TestLdapConnectionResource {
|
|||
|
||||
TestLdapConnectionRepresentation config = new TestLdapConnectionRepresentation(action, connectionUrl, bindDn, bindCredential, useTruststoreSpi, connectionTimeout, startTls, LDAPConstants.AUTH_TYPE_SIMPLE);
|
||||
config.setComponentId(componentId);
|
||||
boolean result = LDAPServerCapabilitiesManager.testLDAP(config, session, realm);
|
||||
return result ? Response.noContent().build() : ErrorResponse.error("LDAP test error", Response.Status.BAD_REQUEST);
|
||||
if (! LDAPServerCapabilitiesManager.testLDAP(config, session, realm)) {
|
||||
throw ErrorResponse.error("LDAP test error", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -84,8 +86,10 @@ public class TestLdapConnectionResource {
|
|||
@NoCache
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public Response testLDAPConnection(TestLdapConnectionRepresentation config) {
|
||||
boolean result = LDAPServerCapabilitiesManager.testLDAP(config, session, realm);
|
||||
return result ? Response.noContent().build() : ErrorResponse.error("LDAP test error", Response.Status.BAD_REQUEST);
|
||||
if (! LDAPServerCapabilitiesManager.testLDAP(config, session, realm)) {
|
||||
throw ErrorResponse.error("LDAP test error", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -22,10 +22,12 @@ import org.keycloak.common.ClientConnection;
|
|||
import org.keycloak.common.util.Time;
|
||||
import org.keycloak.models.ClientModel;
|
||||
import org.keycloak.models.KeycloakSession;
|
||||
import org.keycloak.models.KeycloakSessionFactory;
|
||||
import org.keycloak.models.RealmModel;
|
||||
import org.keycloak.models.UserModel;
|
||||
import org.keycloak.models.UserSessionModel;
|
||||
|
||||
import org.keycloak.models.utils.KeycloakModelUtils;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
@ -42,10 +44,12 @@ public class EventBuilder {
|
|||
|
||||
private static final Logger log = Logger.getLogger(EventBuilder.class);
|
||||
|
||||
private final KeycloakSessionFactory sessionFactory;
|
||||
private EventStoreProvider store;
|
||||
private List<EventListenerProvider> listeners;
|
||||
private RealmModel realm;
|
||||
private Event event;
|
||||
private Boolean storeImmediately;
|
||||
|
||||
public EventBuilder(RealmModel realm, KeycloakSession session, ClientConnection clientConnection) {
|
||||
this(realm, session);
|
||||
|
@ -53,22 +57,23 @@ public class EventBuilder {
|
|||
}
|
||||
|
||||
public EventBuilder(RealmModel realm, KeycloakSession session) {
|
||||
this.sessionFactory = session.getKeycloakSessionFactory();
|
||||
this.realm = realm;
|
||||
|
||||
event = new Event();
|
||||
|
||||
if (realm.isEventsEnabled()) {
|
||||
EventStoreProvider store = session.getProvider(EventStoreProvider.class);
|
||||
if (store != null) {
|
||||
this.store = store;
|
||||
} else {
|
||||
this.store = realm.isEventsEnabled() ? session.getProvider(EventStoreProvider.class) : null;
|
||||
if (realm.isEventsEnabled() && this.store == null) {
|
||||
log.error("Events enabled, but no event store provider configured");
|
||||
}
|
||||
|
||||
this.listeners = getEventListeners(session, realm);
|
||||
|
||||
realm(realm);
|
||||
}
|
||||
|
||||
|
||||
this.listeners = realm.getEventsListenersStream()
|
||||
.map(id -> {
|
||||
private static List<EventListenerProvider> getEventListeners(KeycloakSession session, RealmModel realm) {
|
||||
return realm.getEventsListenersStream().map(id -> {
|
||||
EventListenerProvider listener = session.getProvider(EventListenerProvider.class, id);
|
||||
if (listener != null) {
|
||||
return listener;
|
||||
|
@ -79,15 +84,13 @@ public class EventBuilder {
|
|||
})
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
realm(realm);
|
||||
}
|
||||
|
||||
private EventBuilder(EventStoreProvider store, List<EventListenerProvider> listeners, RealmModel realm, Event event) {
|
||||
this.store = store;
|
||||
private EventBuilder(KeycloakSessionFactory sessionFactory, List<EventListenerProvider> listeners, RealmModel realm, Event event) {
|
||||
this.listeners = listeners;
|
||||
this.realm = realm;
|
||||
this.event = event;
|
||||
this.sessionFactory = sessionFactory;
|
||||
}
|
||||
|
||||
public EventBuilder realm(RealmModel realm) {
|
||||
|
@ -180,6 +183,19 @@ public class EventBuilder {
|
|||
return detail(key, values.filter(Objects::nonNull).collect(Collectors.joining("::")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the time when to store the event.
|
||||
* By default, events marked as success ({@link #success()}) are stored upon commit of the session's transaction
|
||||
* while the failures ({@link #error(java.lang.String)} are stored and propagated to the event listeners
|
||||
* immediately into the event store.
|
||||
* @param forcedValue If {@code true}, the event is stored in the event store immediately. If {@code false},
|
||||
* the event is stored upon commit.
|
||||
* @return
|
||||
*/
|
||||
public EventBuilder storeImmediately(boolean forcedValue) {
|
||||
this.storeImmediately = forcedValue;
|
||||
return this;
|
||||
}
|
||||
|
||||
public EventBuilder removeDetail(String key) {
|
||||
if (event.getDetails() != null) {
|
||||
|
@ -193,7 +209,7 @@ public class EventBuilder {
|
|||
}
|
||||
|
||||
public void success() {
|
||||
send();
|
||||
send(this.storeImmediately == null ? false : this.storeImmediately);
|
||||
}
|
||||
|
||||
public void error(String error) {
|
||||
|
@ -205,26 +221,38 @@ public class EventBuilder {
|
|||
event.setType(EventType.valueOf(event.getType().name() + "_ERROR"));
|
||||
}
|
||||
event.setError(error);
|
||||
send();
|
||||
send(this.storeImmediately == null ? true : this.storeImmediately);
|
||||
}
|
||||
|
||||
public EventBuilder clone() {
|
||||
return new EventBuilder(store, listeners, realm, event.clone());
|
||||
return new EventBuilder(sessionFactory, listeners, realm, event.clone());
|
||||
}
|
||||
|
||||
private void send() {
|
||||
private void send(boolean sendImmediately) {
|
||||
event.setTime(Time.currentTimeMillis());
|
||||
event.setId(UUID.randomUUID().toString());
|
||||
|
||||
if (store != null) {
|
||||
Set<String> eventTypes = realm.getEnabledEventTypesStream().collect(Collectors.toSet());
|
||||
if (!eventTypes.isEmpty() ? eventTypes.contains(event.getType().name()) : event.getType().isSaveByDefault()) {
|
||||
store.onEvent(event);
|
||||
if (sendImmediately) {
|
||||
KeycloakModelUtils.runJobInTransaction(sessionFactory, session -> {
|
||||
EventStoreProvider store = session.getProvider(EventStoreProvider.class);
|
||||
List<EventListenerProvider> listeners = getEventListeners(session, realm);
|
||||
|
||||
sendNow(store, eventTypes, listeners);
|
||||
});
|
||||
} else {
|
||||
sendNow(this.store, eventTypes, this.listeners);
|
||||
}
|
||||
}
|
||||
|
||||
if (listeners != null) {
|
||||
for (EventListenerProvider l : listeners) {
|
||||
private void sendNow(EventStoreProvider targetStore, Set<String> eventTypes, List<EventListenerProvider> targetListeners) {
|
||||
if (targetStore != null) {
|
||||
if (eventTypes.isEmpty() && event.getType().isSaveByDefault() || eventTypes.contains(event.getType().name())) {
|
||||
targetStore.onEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
for (EventListenerProvider l : targetListeners) {
|
||||
try {
|
||||
l.onEvent(event);
|
||||
} catch (Throwable t) {
|
||||
|
@ -232,6 +260,5 @@ public class EventBuilder {
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -126,7 +126,7 @@ public class ScopeService {
|
|||
|
||||
List<Resource> resources = storeFactory.getResourceStore().findByScopes(resourceServer, Collections.singleton(scope));
|
||||
if (!resources.isEmpty()) {
|
||||
return ErrorResponse.error("Scopes can not be removed while associated with resources.", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Scopes can not be removed while associated with resources.", Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -66,8 +66,7 @@ public abstract class AbstractPartialImport<T> implements PartialImport<T> {
|
|||
}
|
||||
|
||||
protected ErrorResponseException existsError(String message) {
|
||||
Response error = ErrorResponse.exists(message);
|
||||
return new ErrorResponseException(error);
|
||||
throw ErrorResponse.exists(message);
|
||||
}
|
||||
|
||||
protected PartialImportResult overwritten(String modelId, T resourceRep){
|
||||
|
|
|
@ -137,14 +137,12 @@ public class ClientRolesPartialImport {
|
|||
}
|
||||
|
||||
protected ErrorResponseException exists(String message) {
|
||||
Response error = ErrorResponse.exists(message);
|
||||
return new ErrorResponseException(error);
|
||||
throw ErrorResponse.exists(message);
|
||||
}
|
||||
|
||||
protected ErrorResponseException noClientFound(String clientId) {
|
||||
String message = "Can not import client roles for nonexistent client named " + clientId;
|
||||
Response error = ErrorResponse.error(message, Response.Status.PRECONDITION_FAILED);
|
||||
return new ErrorResponseException(error);
|
||||
throw ErrorResponse.error(message, Response.Status.PRECONDITION_FAILED);
|
||||
}
|
||||
|
||||
public PartialImportResult overwritten(String clientId, String modelId, RoleRepresentation roleRep) {
|
||||
|
|
|
@ -116,7 +116,7 @@ public class RolesPartialImport implements PartialImport<RolesRepresentation> {
|
|||
RepresentationToModel.importRoles(rep.getRoles(), realm);
|
||||
} catch (Exception e) {
|
||||
ServicesLogger.LOGGER.roleImportError(e);
|
||||
throw new ErrorResponseException(ErrorResponse.error(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR));
|
||||
throw ErrorResponse.error(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
// add "add" results for new roles created
|
||||
|
|
|
@ -28,28 +28,28 @@ import java.util.List;
|
|||
*/
|
||||
public class ErrorResponse {
|
||||
|
||||
public static Response exists(String message) {
|
||||
public static ErrorResponseException exists(String message) {
|
||||
return ErrorResponse.error(message, Response.Status.CONFLICT);
|
||||
}
|
||||
|
||||
public static Response error(String message, Response.Status status) {
|
||||
public static ErrorResponseException error(String message, Response.Status status) {
|
||||
return ErrorResponse.error(message, null, status);
|
||||
}
|
||||
|
||||
public static Response error(String message, Object[] params, Response.Status status) {
|
||||
public static ErrorResponseException error(String message, Object[] params, Response.Status status) {
|
||||
ErrorRepresentation error = new ErrorRepresentation();
|
||||
error.setErrorMessage(message);
|
||||
error.setParams(params);
|
||||
return Response.status(status).entity(error).type(MediaType.APPLICATION_JSON).build();
|
||||
return new ErrorResponseException(Response.status(status).entity(error).type(MediaType.APPLICATION_JSON).build());
|
||||
}
|
||||
|
||||
public static Response errors(List<ErrorRepresentation> s, Response.Status status) {
|
||||
public static ErrorResponseException errors(List<ErrorRepresentation> s, Response.Status status) {
|
||||
return errors(s, status, true);
|
||||
}
|
||||
|
||||
public static Response errors(List<ErrorRepresentation> s, Response.Status status, boolean shrinkSingleError) {
|
||||
public static ErrorResponseException errors(List<ErrorRepresentation> s, Response.Status status, boolean shrinkSingleError) {
|
||||
if (shrinkSingleError && s.size() == 1) {
|
||||
return Response.status(status).entity(s.get(0)).type(MediaType.APPLICATION_JSON).build();
|
||||
return new ErrorResponseException(Response.status(status).entity(s.get(0)).type(MediaType.APPLICATION_JSON).build());
|
||||
}
|
||||
ErrorRepresentation error = new ErrorRepresentation();
|
||||
error.setErrors(s);
|
||||
|
@ -58,6 +58,6 @@ public class ErrorResponse {
|
|||
error.setParams(s.get(0).getParams());
|
||||
error.setField(s.get(0).getField());
|
||||
}
|
||||
return Response.status(status).entity(error).type(MediaType.APPLICATION_JSON).build();
|
||||
return new ErrorResponseException(Response.status(status).entity(error).type(MediaType.APPLICATION_JSON).build());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,6 +17,8 @@
|
|||
|
||||
package org.keycloak.services;
|
||||
|
||||
import org.keycloak.common.util.Resteasy;
|
||||
import org.keycloak.models.KeycloakSession;
|
||||
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
|
||||
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
|
@ -53,6 +55,16 @@ public class ErrorResponseException extends WebApplicationException {
|
|||
|
||||
@Override
|
||||
public Response getResponse() {
|
||||
KeycloakSession session = Resteasy.getContextData(KeycloakSession.class);
|
||||
if (session != null) {
|
||||
// This has to happen, since calling getResponse() with non-null result leads to
|
||||
// directly returning the result instead of
|
||||
// propagating exception to KeycloakErrorHandler.toResponse(Throwable) which would ensure rollback on other exception types.
|
||||
//
|
||||
// See org.jboss.resteasy.core.ExceptionHandler.unwrapException(HttpRequest, Throwable, RESTEasyTracingLogger)
|
||||
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
}
|
||||
if (response != null) {
|
||||
return response;
|
||||
} else {
|
||||
|
|
|
@ -1175,7 +1175,7 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
|
|||
return webEx.getResponse();
|
||||
}
|
||||
|
||||
return ErrorPage.error(this.session, authSession, status, message, parameters);
|
||||
throw new ErrorPageException(this.session, authSession, status, message, parameters);
|
||||
}
|
||||
|
||||
private Response redirectToAccountErrorPage(AuthenticationSessionModel authSession, String message, Object ... parameters) {
|
||||
|
@ -1222,17 +1222,17 @@ public class IdentityBrokerService implements IdentityProvider.AuthenticationCal
|
|||
|
||||
private Response badRequest(String message) {
|
||||
fireErrorEvent(message);
|
||||
return ErrorResponse.error(message, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(message, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
private Response forbidden(String message) {
|
||||
fireErrorEvent(message);
|
||||
return ErrorResponse.error(message, Response.Status.FORBIDDEN);
|
||||
throw ErrorResponse.error(message, Response.Status.FORBIDDEN);
|
||||
}
|
||||
|
||||
private Response notFound(String message) {
|
||||
fireErrorEvent(message);
|
||||
return ErrorResponse.error(message, Response.Status.NOT_FOUND);
|
||||
throw ErrorResponse.error(message, Response.Status.NOT_FOUND);
|
||||
}
|
||||
|
||||
public static IdentityProvider getIdentityProvider(KeycloakSession session, RealmModel realm, String alias) {
|
||||
|
|
|
@ -304,7 +304,7 @@ public class AccountCredentialResource {
|
|||
String label = JsonSerialization.readValue(userLabel, String.class);
|
||||
user.credentialManager().updateCredentialLabel(credentialId, label);
|
||||
} catch (IOException ioe) {
|
||||
throw new ErrorResponseException(ErrorResponse.error(Messages.INVALID_REQUEST, Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(Messages.INVALID_REQUEST, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -774,11 +774,11 @@ public class AccountFormService extends AbstractSecuredLocalService {
|
|||
Resource resource = authorization.getStoreFactory().getResourceStore().findById(realm, null, resourceId);
|
||||
|
||||
if (resource == null) {
|
||||
return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
if (action == null) {
|
||||
return ErrorResponse.error("Invalid action", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Invalid action", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
boolean isGrant = "grant".equals(action);
|
||||
|
@ -901,7 +901,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
|
|||
ResourceServer resourceServer = resource.getResourceServer();
|
||||
|
||||
if (resource == null) {
|
||||
return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
if (userIds == null || userIds.length == 0) {
|
||||
|
@ -988,14 +988,14 @@ public class AccountFormService extends AbstractSecuredLocalService {
|
|||
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
|
||||
|
||||
if (action == null) {
|
||||
return ErrorResponse.error("Invalid action", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Invalid action", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
for (String resourceId : resourceIds) {
|
||||
Resource resource = authorization.getStoreFactory().getResourceStore().findById(realm, null, resourceId);
|
||||
|
||||
if (resource == null) {
|
||||
return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
|
||||
|
|
|
@ -229,9 +229,9 @@ public class AccountRestService {
|
|||
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);
|
||||
throw ErrorResponse.errors(errors, pve.getStatusCode(), false);
|
||||
} catch (ReadOnlyException e) {
|
||||
return ErrorResponse.error(Messages.READ_ONLY_USER, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(Messages.READ_ONLY_USER, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -335,7 +335,7 @@ public class AccountRestService {
|
|||
|
||||
ClientModel client = realm.getClientByClientId(clientId);
|
||||
if (client == null) {
|
||||
return ErrorResponse.error("No client with clientId: " + clientId + " found.", Response.Status.NOT_FOUND);
|
||||
throw ErrorResponse.error("No client with clientId: " + clientId + " found.", Response.Status.NOT_FOUND);
|
||||
}
|
||||
|
||||
UserConsentModel consent = session.users().getConsentByClient(realm, user.getId(), client.getId());
|
||||
|
@ -363,7 +363,7 @@ public class AccountRestService {
|
|||
if (client == null) {
|
||||
String msg = String.format("No client with clientId: %s found.", clientId);
|
||||
event.error(msg);
|
||||
return ErrorResponse.error(msg, Response.Status.NOT_FOUND);
|
||||
throw ErrorResponse.error(msg, Response.Status.NOT_FOUND);
|
||||
}
|
||||
|
||||
UserConsentManager.revokeConsentToClient(session, client, user);
|
||||
|
@ -422,7 +422,7 @@ public class AccountRestService {
|
|||
if (client == null) {
|
||||
String msg = String.format("No client with clientId: %s found.", clientId);
|
||||
event.error(msg);
|
||||
return ErrorResponse.error(msg, Response.Status.NOT_FOUND);
|
||||
throw ErrorResponse.error(msg, Response.Status.NOT_FOUND);
|
||||
}
|
||||
|
||||
try {
|
||||
|
@ -440,7 +440,7 @@ public class AccountRestService {
|
|||
grantedConsent = session.users().getConsentByClient(realm, user.getId(), client.getId());
|
||||
return Response.ok(modelToRepresentation(grantedConsent)).build();
|
||||
} catch (IllegalArgumentException e) {
|
||||
return ErrorResponse.error(e.getMessage(), Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(e.getMessage(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -154,10 +154,10 @@ public class LinkedAccountsResource {
|
|||
|
||||
String errorMessage = checkCommonPreconditions(providerId);
|
||||
if (errorMessage != null) {
|
||||
return ErrorResponse.error(errorMessage, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(errorMessage, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
if (auth.getSession() == null) {
|
||||
return ErrorResponse.error(Messages.SESSION_NOT_ACTIVE, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(Messages.SESSION_NOT_ACTIVE, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
try {
|
||||
|
@ -184,7 +184,7 @@ public class LinkedAccountsResource {
|
|||
return Cors.add(request, Response.ok(rep)).auth().allowedOrigins(auth.getToken()).build();
|
||||
} catch (Exception spe) {
|
||||
spe.printStackTrace();
|
||||
return ErrorResponse.error(Messages.FAILED_TO_PROCESS_RESPONSE, Response.Status.INTERNAL_SERVER_ERROR);
|
||||
throw ErrorResponse.error(Messages.FAILED_TO_PROCESS_RESPONSE, Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -196,17 +196,17 @@ public class LinkedAccountsResource {
|
|||
|
||||
String errorMessage = checkCommonPreconditions(providerId);
|
||||
if (errorMessage != null) {
|
||||
return ErrorResponse.error(errorMessage, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(errorMessage, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
FederatedIdentityModel link = session.users().getFederatedIdentity(realm, user, providerId);
|
||||
if (link == null) {
|
||||
return ErrorResponse.error(Messages.FEDERATED_IDENTITY_NOT_ACTIVE, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(Messages.FEDERATED_IDENTITY_NOT_ACTIVE, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Removing last social provider is not possible if you don't have other possibility to authenticate
|
||||
if (!(session.users().getFederatedIdentitiesStream(realm, user).count() > 1 || user.getFederationLink() != null || isPasswordSet())) {
|
||||
return ErrorResponse.error(Messages.FEDERATED_IDENTITY_REMOVING_LAST_PROVIDER, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(Messages.FEDERATED_IDENTITY_REMOVING_LAST_PROVIDER, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
session.users().removeFederatedIdentity(realm, user, providerId);
|
||||
|
|
|
@ -204,11 +204,11 @@ public class AuthenticationManagementResource {
|
|||
auth.realm().requireManageRealm();
|
||||
|
||||
if (flow.getAlias() == null || flow.getAlias().isEmpty()) {
|
||||
return ErrorResponse.exists("Failed to create flow with empty alias name");
|
||||
throw ErrorResponse.exists("Failed to create flow with empty alias name");
|
||||
}
|
||||
|
||||
if (realm.getFlowByAlias(flow.getAlias()) != null) {
|
||||
return ErrorResponse.exists("Flow " + flow.getAlias() + " already exists");
|
||||
throw ErrorResponse.exists("Flow " + flow.getAlias() + " already exists");
|
||||
}
|
||||
|
||||
ReservedCharValidator.validate(flow.getAlias());
|
||||
|
@ -257,7 +257,7 @@ public class AuthenticationManagementResource {
|
|||
AuthenticationFlowRepresentation existingFlow = getFlow(id);
|
||||
|
||||
if (flow.getAlias() == null || flow.getAlias().isEmpty()) {
|
||||
return ErrorResponse.exists("Failed to update flow with empty alias name");
|
||||
throw ErrorResponse.exists("Failed to update flow with empty alias name");
|
||||
}
|
||||
|
||||
//check if updating a correct flow
|
||||
|
@ -269,7 +269,7 @@ public class AuthenticationManagementResource {
|
|||
|
||||
//if a different flow with the same name does already exist, throw an exception
|
||||
if (realm.getFlowByAlias(flow.getAlias()) != null && !checkFlow.getAlias().equals(flow.getAlias())) {
|
||||
return ErrorResponse.exists("Flow alias name already exists");
|
||||
throw ErrorResponse.exists("Flow alias name already exists");
|
||||
}
|
||||
|
||||
//if the name changed
|
||||
|
@ -344,7 +344,7 @@ public class AuthenticationManagementResource {
|
|||
|
||||
String newName = data.get("newName");
|
||||
if (realm.getFlowByAlias(newName) != null) {
|
||||
return ErrorResponse.exists("New flow alias name already exists");
|
||||
throw ErrorResponse.exists("New flow alias name already exists");
|
||||
}
|
||||
|
||||
AuthenticationFlowModel flow = realm.getFlowByAlias(flowAlias);
|
||||
|
@ -408,7 +408,7 @@ public class AuthenticationManagementResource {
|
|||
|
||||
AuthenticationFlowModel parentFlow = realm.getFlowByAlias(flowAlias);
|
||||
if (parentFlow == null) {
|
||||
return ErrorResponse.error("Parent flow doesn't exist", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Parent flow doesn't exist", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
String alias = data.get("alias");
|
||||
String type = data.get("type");
|
||||
|
@ -418,7 +418,7 @@ public class AuthenticationManagementResource {
|
|||
|
||||
AuthenticationFlowModel newFlow = realm.getFlowByAlias(alias);
|
||||
if (newFlow != null) {
|
||||
return ErrorResponse.exists("New flow alias name already exists");
|
||||
throw ErrorResponse.exists("New flow alias name already exists");
|
||||
}
|
||||
newFlow = new AuthenticationFlowModel();
|
||||
newFlow.setAlias(alias);
|
||||
|
@ -663,7 +663,7 @@ public class AuthenticationManagementResource {
|
|||
|
||||
//if a different flow with the same name does already exist, throw an exception
|
||||
if (realm.getFlowByAlias(rep.getDisplayName()) != null && !checkFlow.getAlias().equals(rep.getDisplayName())) {
|
||||
return ErrorResponse.exists("Flow alias name already exists");
|
||||
throw ErrorResponse.exists("Flow alias name already exists");
|
||||
}
|
||||
|
||||
//if the name changed
|
||||
|
@ -876,7 +876,7 @@ public class AuthenticationManagementResource {
|
|||
}
|
||||
AuthenticatorConfigModel config = RepresentationToModel.toModel(json);
|
||||
if (config.getAlias() == null) {
|
||||
return ErrorResponse.error("Alias missing", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Alias missing", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
config = realm.addAuthenticatorConfig(config);
|
||||
model.setAuthenticatorConfig(config.getId());
|
||||
|
|
|
@ -65,7 +65,7 @@ public class ClientPoliciesResource {
|
|||
try {
|
||||
return session.clientPolicy().getClientPolicies(realm);
|
||||
} catch (ClientPolicyException e) {
|
||||
throw new BadRequestException(ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -77,7 +77,7 @@ public class ClientPoliciesResource {
|
|||
try {
|
||||
session.clientPolicy().updateClientPolicies(realm, clientPolicies);
|
||||
} catch (ClientPolicyException e) {
|
||||
return ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
|
|
@ -66,7 +66,7 @@ public class ClientProfilesResource {
|
|||
try {
|
||||
return session.clientPolicy().getClientProfiles(realm, includeGlobalProfiles);
|
||||
} catch (ClientPolicyException e) {
|
||||
throw new BadRequestException(ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -78,7 +78,7 @@ public class ClientProfilesResource {
|
|||
try {
|
||||
session.clientPolicy().updateClientProfiles(realm, clientProfiles);
|
||||
} catch (ClientPolicyException e) {
|
||||
return ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(e.getError(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
|
|
@ -160,7 +160,7 @@ public class ClientResource {
|
|||
adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();
|
||||
return Response.noContent().build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Client already exists");
|
||||
throw ErrorResponse.exists("Client already exists");
|
||||
} catch (ClientPolicyException cpe) {
|
||||
throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
|
|
@ -111,7 +111,7 @@ public class ClientScopeResource {
|
|||
}
|
||||
return Response.noContent().build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Client Scope " + rep.getName() + " already exists");
|
||||
throw ErrorResponse.exists("Client Scope " + rep.getName() + " already exists");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -144,7 +144,7 @@ public class ClientScopeResource {
|
|||
adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).success();
|
||||
return Response.noContent().build();
|
||||
} catch (ModelException me) {
|
||||
return ErrorResponse.error(me.getMessage(), Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(me.getMessage(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -163,24 +163,24 @@ public class ClientScopeResource {
|
|||
if (Profile.isFeatureEnabled(Profile.Feature.DYNAMIC_SCOPES)) {
|
||||
// if the scope is dynamic but the regexp is empty, it's not considered valid
|
||||
if (isDynamic && StringUtil.isNullOrEmpty(regexp)) {
|
||||
throw new ErrorResponseException(ErrorResponse.error("Dynamic scope regexp must not be null or empty", Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("Dynamic scope regexp must not be null or empty", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
// Always validate the dynamic scope regexp to avoid inserting a wrong value even when the feature is disabled
|
||||
if (!StringUtil.isNullOrEmpty(regexp) && !dynamicScreenPattern.matcher(regexp).matches()) {
|
||||
throw new ErrorResponseException(ErrorResponse.error(String.format("Invalid format for the Dynamic Scope regexp %1s", regexp), Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(String.format("Invalid format for the Dynamic Scope regexp %1s", regexp), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
} else {
|
||||
// if the value is not null or empty we won't accept the request as the feature is disabled
|
||||
Optional.ofNullable(regexp).ifPresent(s -> {
|
||||
if (!s.isEmpty()) {
|
||||
throw new ErrorResponseException(ErrorResponse.error(String.format("Unexpected value \"%1s\" for attribute %2s in ClientScope",
|
||||
regexp, ClientScopeModel.DYNAMIC_SCOPE_REGEXP), Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(String.format("Unexpected value \"%1s\" for attribute %2s in ClientScope",
|
||||
regexp, ClientScopeModel.DYNAMIC_SCOPE_REGEXP), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
});
|
||||
// If isDynamic is true, we won't accept the request as the feature is disabled
|
||||
if (isDynamic) {
|
||||
throw new ErrorResponseException(ErrorResponse.error(String.format("Unexpected value \"%1s\" for attribute %2s in ClientScope",
|
||||
isDynamic, ClientScopeModel.IS_DYNAMIC_SCOPE), Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(String.format("Unexpected value \"%1s\" for attribute %2s in ClientScope",
|
||||
isDynamic, ClientScopeModel.IS_DYNAMIC_SCOPE), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -188,7 +188,7 @@ public class ClientScopeResource {
|
|||
public static void validateClientScopeName(String name) throws ErrorResponseException {
|
||||
if (!scopeNamePattern.matcher(name).matches()) {
|
||||
String message = String.format("Unexpected name \"%s\" for ClientScope", name);
|
||||
throw new ErrorResponseException(ErrorResponse.error(message, Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(message, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -209,8 +209,8 @@ public class ClientScopeResource {
|
|||
.findAny();
|
||||
// if it's present, it means that a client has this scope assigned as a default scope, so this scope can't be made dynamic
|
||||
if (scopeModelOpt.isPresent()) {
|
||||
throw new ErrorResponseException(ErrorResponse.error("This Client Scope can't be made dynamic as it's assigned to a Client as a Default Scope",
|
||||
Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("This Client Scope can't be made dynamic as it's assigned to a Client as a Default Scope",
|
||||
Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
// after the previous validation, run the usual Dynamic Scope validations.
|
||||
|
|
|
@ -101,7 +101,7 @@ public class ClientScopesResource {
|
|||
|
||||
return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(clientModel.getId()).build()).build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Client Scope " + rep.getName() + " already exists");
|
||||
throw ErrorResponse.exists("Client Scope " + rep.getName() + " already exists");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -210,7 +210,7 @@ public class ClientsResource {
|
|||
|
||||
return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(clientModel.getId()).build()).build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Client " + rep.getClientId() + " already exists");
|
||||
throw ErrorResponse.exists("Client " + rep.getClientId() + " already exists");
|
||||
} catch (ClientPolicyException cpe) {
|
||||
throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
|
|
@ -214,7 +214,7 @@ public class ComponentResource {
|
|||
}).toArray();
|
||||
|
||||
String message = MessageFormat.format(messages.getProperty(cve.getMessage(), cve.getMessage()), localizedParameters);
|
||||
return ErrorResponse.error(message, Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(message, Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -104,14 +104,14 @@ public class GroupResource {
|
|||
|
||||
String groupName = rep.getName();
|
||||
if (ObjectUtil.isBlank(groupName)) {
|
||||
return ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
if (!Objects.equals(groupName, group.getName())) {
|
||||
boolean exists = siblings().filter(s -> !Objects.equals(s.getId(), group.getId()))
|
||||
.anyMatch(s -> Objects.equals(s.getName(), groupName));
|
||||
if (exists) {
|
||||
return ErrorResponse.exists("Sibling group named '" + groupName + "' already exists.");
|
||||
throw ErrorResponse.exists("Sibling group named '" + groupName + "' already exists.");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -154,11 +154,11 @@ public class GroupResource {
|
|||
|
||||
String groupName = rep.getName();
|
||||
if (ObjectUtil.isBlank(groupName)) {
|
||||
return ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
boolean childExists = group.getSubGroupsStream().anyMatch(s -> Objects.equals(s.getName(), groupName));
|
||||
if (childExists) {
|
||||
return ErrorResponse.exists("Sibling group named '" + groupName + "' already exists.");
|
||||
throw ErrorResponse.exists("Sibling group named '" + groupName + "' already exists.");
|
||||
}
|
||||
|
||||
Response.ResponseBuilder builder = Response.status(204);
|
||||
|
|
|
@ -147,7 +147,7 @@ public class GroupsResource {
|
|||
String groupName = rep.getName();
|
||||
|
||||
if (ObjectUtil.isBlank(groupName)) {
|
||||
return ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
try {
|
||||
|
@ -169,7 +169,7 @@ public class GroupsResource {
|
|||
adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), child.getId());
|
||||
}
|
||||
} catch (ModelDuplicateException mde) {
|
||||
return ErrorResponse.exists("Top level group named '" + groupName + "' already exists.");
|
||||
throw ErrorResponse.exists("Top level group named '" + groupName + "' already exists.");
|
||||
}
|
||||
|
||||
adminEvent.representation(rep).success();
|
||||
|
|
|
@ -165,9 +165,9 @@ public class IdentityProviderResource {
|
|||
message = "Invalid request";
|
||||
}
|
||||
|
||||
return ErrorResponse.error(message, BAD_REQUEST);
|
||||
throw ErrorResponse.error(message, BAD_REQUEST);
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Identity Provider " + providerRep.getAlias() + " already exists");
|
||||
throw ErrorResponse.exists("Identity Provider " + providerRep.getAlias() + " already exists");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -261,7 +261,7 @@ public class IdentityProviderResource {
|
|||
IdentityProviderFactory factory = getIdentityProviderFactory();
|
||||
return factory.create(session, identityProviderModel).export(session.getContext().getUri(), realm, format);
|
||||
} catch (Exception e) {
|
||||
return ErrorResponse.error("Could not export public broker configuration for identity provider [" + identityProviderModel.getProviderId() + "].", Response.Status.NOT_FOUND);
|
||||
throw ErrorResponse.error("Could not export public broker configuration for identity provider [" + identityProviderModel.getProviderId() + "].", Response.Status.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -339,7 +339,7 @@ public class IdentityProviderResource {
|
|||
try {
|
||||
model = realm.addIdentityProviderMapper(model);
|
||||
} catch (Exception e) {
|
||||
return ErrorResponse.error("Failed to add mapper '" + model.getName() + "' to identity provider [" + identityProviderModel.getProviderId() + "].", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Failed to add mapper '" + model.getName() + "' to identity provider [" + identityProviderModel.getProviderId() + "].", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
adminEvent.operation(OperationType.CREATE).resource(ResourceType.IDENTITY_PROVIDER_MAPPER).resourcePath(session.getContext().getUri(), model.getId())
|
||||
|
|
|
@ -199,9 +199,9 @@ public class IdentityProvidersResource {
|
|||
message = "Invalid request";
|
||||
}
|
||||
|
||||
return ErrorResponse.error(message, BAD_REQUEST);
|
||||
throw ErrorResponse.error(message, BAD_REQUEST);
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Identity Provider " + representation.getAlias() + " already exists");
|
||||
throw ErrorResponse.exists("Identity Provider " + representation.getAlias() + " already exists");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -127,7 +127,7 @@ public class ProtocolMappersResource {
|
|||
adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), model.getId()).representation(rep).success();
|
||||
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Protocol mapper exists with same name");
|
||||
throw ErrorResponse.exists("Protocol mapper exists with same name");
|
||||
}
|
||||
|
||||
return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(model.getId()).build()).build();
|
||||
|
|
|
@ -391,7 +391,7 @@ public class RealmAdminResource {
|
|||
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);
|
||||
throw ErrorResponse.error("Can't rename master realm", Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
ReservedCharValidator.validate(rep.getRealm());
|
||||
|
@ -402,7 +402,7 @@ public class RealmAdminResource {
|
|||
try {
|
||||
KeyPairVerifier.verify(rep.getPrivateKey(), rep.getPublicKey());
|
||||
} catch (VerificationException e) {
|
||||
return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -410,10 +410,10 @@ public class RealmAdminResource {
|
|||
try {
|
||||
X509Certificate cert = PemUtils.decodeCertificate(rep.getCertificate());
|
||||
if (cert == null) {
|
||||
return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -434,12 +434,12 @@ public class RealmAdminResource {
|
|||
|
||||
return Response.noContent().build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Realm with same name exists");
|
||||
throw ErrorResponse.exists("Realm with same name exists");
|
||||
} catch (ModelException e) {
|
||||
return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
|
||||
throw 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);
|
||||
throw ErrorResponse.error("Failed to update realm", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -930,7 +930,7 @@ public class RealmAdminResource {
|
|||
try {
|
||||
UserModel user = auth.adminAuth().getUser();
|
||||
if (user.getEmail() == null) {
|
||||
return ErrorResponse.error("Logged in user does not have an e-mail.", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
throw ErrorResponse.error("Logged in user does not have an e-mail.", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
if (ComponentRepresentation.SECRET_VALUE.equals(settings.get("password"))) {
|
||||
settings.put("password", realm.getSmtpConfig().get("password"));
|
||||
|
@ -939,7 +939,7 @@ public class RealmAdminResource {
|
|||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.errorf("Failed to send email \n %s", e.getCause());
|
||||
return ErrorResponse.error("Failed to send email", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
throw ErrorResponse.error("Failed to send email", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
return Response.noContent().build();
|
||||
|
@ -1035,11 +1035,11 @@ public class RealmAdminResource {
|
|||
})
|
||||
).build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists(e.getLocalizedMessage());
|
||||
throw ErrorResponse.exists(e.getLocalizedMessage());
|
||||
} catch (ErrorResponseException error) {
|
||||
return error.getResponse();
|
||||
} catch (Exception e) {
|
||||
return ErrorResponse.error(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
|
||||
throw ErrorResponse.error(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -150,11 +150,11 @@ public class RealmsAdminResource {
|
|||
} catch (ModelDuplicateException e) {
|
||||
logger.error("Conflict detected", e);
|
||||
if (session.getTransactionManager().isActive()) session.getTransactionManager().setRollbackOnly();
|
||||
return ErrorResponse.exists("Conflict detected. See logs for details");
|
||||
throw ErrorResponse.exists("Conflict detected. See logs for details");
|
||||
} catch (PasswordPolicyNotMetException e) {
|
||||
logger.error("Password policy not met for user " + e.getUsername(), e);
|
||||
if (session.getTransactionManager().isActive()) session.getTransactionManager().setRollbackOnly();
|
||||
return ErrorResponse.error("Password policy not met. See logs for details", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Password policy not met. See logs for details", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -108,8 +108,8 @@ public class RoleByIdResource extends RoleResource {
|
|||
if (realm.getDefaultRole() == null) {
|
||||
logger.warnf("Default role for realm with id '%s' doesn't exist.", realm.getId());
|
||||
} else if (realm.getDefaultRole().getId().equals(id)) {
|
||||
throw new ErrorResponseException(ErrorResponse.error(realm.getDefaultRole().getName() + " is default role of the realm and cannot be removed.",
|
||||
Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(realm.getDefaultRole().getName() + " is default role of the realm and cannot be removed.",
|
||||
Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
RoleModel role = getRoleModel(id);
|
||||
|
|
|
@ -164,7 +164,7 @@ public class RoleContainerResource extends RoleResource {
|
|||
for (String roleName : compositeRealmRoles) {
|
||||
RoleModel realmRole = realm.getRole(roleName);
|
||||
if (realmRole == null) {
|
||||
return ErrorResponse.error("Realm Role with name " + roleName + " does not exist", Response.Status.NOT_FOUND);
|
||||
throw ErrorResponse.error("Realm Role with name " + roleName + " does not exist", Response.Status.NOT_FOUND);
|
||||
}
|
||||
realmRoles.add(realmRole);
|
||||
}
|
||||
|
@ -185,7 +185,7 @@ public class RoleContainerResource extends RoleResource {
|
|||
for (String roleName : clientRoleNames) {
|
||||
RoleModel clientRole = client.getRole(roleName);
|
||||
if (clientRole == null) {
|
||||
return ErrorResponse.error("Client Role with name " + roleName + " does not exist", Response.Status.NOT_FOUND);
|
||||
throw ErrorResponse.error("Client Role with name " + roleName + " does not exist", Response.Status.NOT_FOUND);
|
||||
}
|
||||
clientRoles.add(clientRole);
|
||||
}
|
||||
|
@ -198,7 +198,7 @@ public class RoleContainerResource extends RoleResource {
|
|||
|
||||
return Response.created(uriInfo.getAbsolutePathBuilder().path(role.getName()).build()).build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Role with name " + rep.getName() + " already exists");
|
||||
throw ErrorResponse.exists("Role with name " + rep.getName() + " already exists");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -237,8 +237,8 @@ public class RoleContainerResource extends RoleResource {
|
|||
if (role == null) {
|
||||
throw new NotFoundException("Could not find role");
|
||||
} else if (realm.getDefaultRole().getId().equals(role.getId())) {
|
||||
throw new ErrorResponseException(ErrorResponse.error(roleName + " is default role of the realm and cannot be removed.",
|
||||
Response.Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error(roleName + " is default role of the realm and cannot be removed.",
|
||||
Response.Status.BAD_REQUEST);
|
||||
}
|
||||
deleteRole(role);
|
||||
|
||||
|
@ -281,7 +281,7 @@ public class RoleContainerResource extends RoleResource {
|
|||
|
||||
return Response.noContent().build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("Role with name " + rep.getName() + " already exists");
|
||||
throw ErrorResponse.exists("Role with name " + rep.getName() + " already exists");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -63,7 +63,7 @@ public class UserProfileResource {
|
|||
t.setConfiguration(text);
|
||||
} catch (ComponentValidationException e) {
|
||||
//show validation result containing details about error
|
||||
return ErrorResponse.error(e.getMessage(), Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error(e.getMessage(), Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
return Response.ok(t.getConfiguration()).type(MediaType.APPLICATION_JSON).build();
|
||||
|
|
|
@ -207,21 +207,21 @@ public class UserResource {
|
|||
return Response.noContent().build();
|
||||
} catch (ModelDuplicateException e) {
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
return ErrorResponse.exists("User exists with same username or email");
|
||||
throw ErrorResponse.exists("User exists with same username or email");
|
||||
} catch (ReadOnlyException re) {
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
return ErrorResponse.error("User is read only!", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("User is read only!", Status.BAD_REQUEST);
|
||||
} catch (ModelException me) {
|
||||
logger.warn("Could not update user!", me);
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
return ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
|
||||
} catch (ForbiddenException fe) {
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
throw fe;
|
||||
} catch (Exception me) { // JPA
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
logger.warn("Could not update user!", me);// may be committed by JTA which can't
|
||||
return ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Could not update user!", Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -235,7 +235,7 @@ public class UserResource {
|
|||
errors.add(new ErrorRepresentation(error.getFormattedMessage(new AdminMessageFormatter(session, user))));
|
||||
}
|
||||
|
||||
return ErrorResponse.errors(errors, Status.BAD_REQUEST);
|
||||
throw ErrorResponse.errors(errors, Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
@ -428,7 +428,7 @@ public class UserResource {
|
|||
public Response addFederatedIdentity(final @PathParam("provider") String provider, FederatedIdentityRepresentation rep) {
|
||||
auth.users().requireManage(user);
|
||||
if (session.users().getFederatedIdentity(realm, user, provider) != null) {
|
||||
return ErrorResponse.exists("User is already linked with provider");
|
||||
throw ErrorResponse.exists("User is already linked with provider");
|
||||
}
|
||||
|
||||
FederatedIdentityModel socialLink = new FederatedIdentityModel(provider, rep.getUserId(), rep.getUserName());
|
||||
|
@ -578,7 +578,7 @@ public class UserResource {
|
|||
adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).success();
|
||||
return Response.noContent().build();
|
||||
} else {
|
||||
return ErrorResponse.error("User couldn't be deleted", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("User couldn't be deleted", Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -788,17 +788,15 @@ public class UserResource {
|
|||
auth.users().requireManage(user);
|
||||
|
||||
if (user.getEmail() == null) {
|
||||
return ErrorResponse.error("User email missing", Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("User email missing", Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
if (!user.isEnabled()) {
|
||||
throw new WebApplicationException(
|
||||
ErrorResponse.error("User is disabled", Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("User is disabled", Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
if (redirectUri != null && clientId == null) {
|
||||
throw new WebApplicationException(
|
||||
ErrorResponse.error("Client id missing", Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("Client id missing", Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
if (clientId == null) {
|
||||
|
@ -806,28 +804,24 @@ public class UserResource {
|
|||
}
|
||||
|
||||
if (CollectionUtil.isNotEmpty(actions) && !RequiredActionsValidator.validRequiredActions(session, actions)) {
|
||||
throw new WebApplicationException(
|
||||
ErrorResponse.error("Provided invalid required actions", Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("Provided invalid required actions", Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
ClientModel client = realm.getClientByClientId(clientId);
|
||||
if (client == null) {
|
||||
logger.debugf("Client %s doesn't exist", clientId);
|
||||
throw new WebApplicationException(
|
||||
ErrorResponse.error("Client doesn't exist", Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("Client doesn't exist", Status.BAD_REQUEST);
|
||||
}
|
||||
if (!client.isEnabled()) {
|
||||
logger.debugf("Client %s is not enabled", clientId);
|
||||
throw new WebApplicationException(
|
||||
ErrorResponse.error("Client is not enabled", Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("Client is not enabled", Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
String redirect;
|
||||
if (redirectUri != null) {
|
||||
redirect = RedirectUtils.verifyRedirectUri(session, redirectUri, client);
|
||||
if (redirect == null) {
|
||||
throw new WebApplicationException(
|
||||
ErrorResponse.error("Invalid redirect uri.", Status.BAD_REQUEST));
|
||||
throw ErrorResponse.error("Invalid redirect uri.", Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -856,7 +850,7 @@ public class UserResource {
|
|||
return Response.noContent().build();
|
||||
} catch (EmailException e) {
|
||||
ServicesLogger.LOGGER.failedToSendActionsEmail(e);
|
||||
return ErrorResponse.error("Failed to send execute actions email", Status.INTERNAL_SERVER_ERROR);
|
||||
throw ErrorResponse.error("Failed to send execute actions email", Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -126,20 +126,20 @@ public class UsersResource {
|
|||
username = rep.getEmail();
|
||||
}
|
||||
if (ObjectUtil.isBlank(username)) {
|
||||
return ErrorResponse.error("User name is missing", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("User name is missing", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Double-check duplicated username and email here due to federation
|
||||
if (session.users().getUserByUsername(realm, username) != null) {
|
||||
return ErrorResponse.exists("User exists with same username");
|
||||
throw ErrorResponse.exists("User exists with same username");
|
||||
}
|
||||
if (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed()) {
|
||||
try {
|
||||
if(session.users().getUserByEmail(realm, rep.getEmail()) != null) {
|
||||
return ErrorResponse.exists("User exists with same email");
|
||||
throw ErrorResponse.exists("User exists with same email");
|
||||
}
|
||||
} catch (ModelDuplicateException e) {
|
||||
return ErrorResponse.exists("User exists with same email");
|
||||
throw ErrorResponse.exists("User exists with same email");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -171,18 +171,18 @@ public class UsersResource {
|
|||
if (session.getTransactionManager().isActive()) {
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
}
|
||||
return ErrorResponse.exists("User exists with same username or email");
|
||||
throw ErrorResponse.exists("User exists with same username or email");
|
||||
} catch (PasswordPolicyNotMetException e) {
|
||||
if (session.getTransactionManager().isActive()) {
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
}
|
||||
return ErrorResponse.error("Password policy not met", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Password policy not met", Response.Status.BAD_REQUEST);
|
||||
} catch (ModelException me){
|
||||
if (session.getTransactionManager().isActive()) {
|
||||
session.getTransactionManager().setRollbackOnly();
|
||||
}
|
||||
logger.warn("Could not create user", me);
|
||||
return ErrorResponse.error("Could not create user", Response.Status.BAD_REQUEST);
|
||||
throw ErrorResponse.error("Could not create user", Response.Status.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -324,7 +324,7 @@ public class TestingResourceProvider implements RealmResourceProvider {
|
|||
EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
|
||||
RealmModel realm = session.realms().getRealm(realmId);
|
||||
|
||||
if (realm == null) return ErrorResponse.error("Realm not found", Response.Status.NOT_FOUND);
|
||||
if (realm == null) throw ErrorResponse.error("Realm not found", Response.Status.NOT_FOUND);
|
||||
|
||||
eventStore.clear(realm);
|
||||
return Response.noContent().build();
|
||||
|
@ -453,7 +453,7 @@ public class TestingResourceProvider implements RealmResourceProvider {
|
|||
EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
|
||||
RealmModel realm = session.realms().getRealm(realmId);
|
||||
|
||||
if (realm == null) return ErrorResponse.error("Realm not found", Response.Status.NOT_FOUND);
|
||||
if (realm == null) throw ErrorResponse.error("Realm not found", Response.Status.NOT_FOUND);
|
||||
|
||||
eventStore.clearAdmin(realm);
|
||||
return Response.noContent().build();
|
||||
|
@ -466,7 +466,7 @@ public class TestingResourceProvider implements RealmResourceProvider {
|
|||
EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
|
||||
RealmModel realm = session.realms().getRealm(realmId);
|
||||
|
||||
if (realm == null) return ErrorResponse.error("Realm not found", Response.Status.NOT_FOUND);
|
||||
if (realm == null) throw ErrorResponse.error("Realm not found", Response.Status.NOT_FOUND);
|
||||
|
||||
eventStore.clearAdmin(realm, olderThan);
|
||||
return Response.noContent().build();
|
||||
|
|
|
@ -76,8 +76,8 @@ public class EventQueryTest extends KeycloakModelTest {
|
|||
});
|
||||
}
|
||||
|
||||
private Event createAuthEventForUser(RealmModel realm, String user) {
|
||||
return new EventBuilder(realm, null, DummyClientConnection.DUMMY_CONNECTION)
|
||||
private Event createAuthEventForUser(KeycloakSession session, RealmModel realm, String user) {
|
||||
return new EventBuilder(realm, session, DummyClientConnection.DUMMY_CONNECTION)
|
||||
.event(EventType.LOGIN)
|
||||
.user(user)
|
||||
.getEvent();
|
||||
|
@ -88,10 +88,10 @@ public class EventQueryTest extends KeycloakModelTest {
|
|||
withRealm(realmId, (session, realm) -> {
|
||||
EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
|
||||
|
||||
eventStore.onEvent(createAuthEventForUser(realm,"u1"));
|
||||
eventStore.onEvent(createAuthEventForUser(realm,"u2"));
|
||||
eventStore.onEvent(createAuthEventForUser(realm,"u3"));
|
||||
eventStore.onEvent(createAuthEventForUser(realm,"u4"));
|
||||
eventStore.onEvent(createAuthEventForUser(session, realm, "u1"));
|
||||
eventStore.onEvent(createAuthEventForUser(session, realm, "u2"));
|
||||
eventStore.onEvent(createAuthEventForUser(session, realm, "u3"));
|
||||
eventStore.onEvent(createAuthEventForUser(session, realm, "u4"));
|
||||
|
||||
return realm.getId();
|
||||
});
|
||||
|
@ -115,9 +115,9 @@ public class EventQueryTest extends KeycloakModelTest {
|
|||
withRealm(realmId, (session, realm) -> {
|
||||
EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
|
||||
|
||||
Event firstEvent = createAuthEventForUser(realm, "u1");
|
||||
Event firstEvent = createAuthEventForUser(session, realm, "u1");
|
||||
firstEvent.setTime(1L);
|
||||
Event secondEvent = createAuthEventForUser(realm, "u2");
|
||||
Event secondEvent = createAuthEventForUser(session, realm, "u2");
|
||||
secondEvent.setTime(2L);
|
||||
eventStore.onEvent(firstEvent);
|
||||
eventStore.onEvent(secondEvent);
|
||||
|
@ -158,12 +158,12 @@ public class EventQueryTest extends KeycloakModelTest {
|
|||
|
||||
// Set expiration so no event is valid
|
||||
realm.setEventsExpiration(5);
|
||||
Event e = createAuthEventForUser(realm, "u1");
|
||||
Event e = createAuthEventForUser(session, realm, "u1");
|
||||
eventStore.onEvent(e);
|
||||
|
||||
// Set expiration to 1000 seconds
|
||||
realm.setEventsExpiration(1000);
|
||||
e = createAuthEventForUser(realm, "u2");
|
||||
e = createAuthEventForUser(session, realm, "u2");
|
||||
eventStore.onEvent(e);
|
||||
|
||||
return null;
|
||||
|
@ -199,7 +199,7 @@ public class EventQueryTest extends KeycloakModelTest {
|
|||
realm.setDefaultRole(session.roles().addRealmRole(realm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm.getName()));
|
||||
|
||||
EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
|
||||
Event e = createAuthEventForUser(realm, "u1");
|
||||
Event e = createAuthEventForUser(session, realm, "u1");
|
||||
eventStore.onEvent(e);
|
||||
|
||||
AdminEvent ae = new AdminEvent();
|
||||
|
|
Loading…
Reference in a new issue