use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class MapPermissionTicketStore method create.
@Override
public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
LOG.tracef("create(%s, %s, %s, %s)%s", resourceId, scopeId, requester, resourceServer, getShortStackTrace());
String owner = authorizationProvider.getStoreFactory().getResourceStore().findById(resourceId, resourceServer.getId()).getOwner();
// @UniqueConstraint(columnNames = {"OWNER", "REQUESTER", "RESOURCE_SERVER_ID", "RESOURCE_ID", "SCOPE_ID"})
DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServer.getId()).compare(SearchableFields.OWNER, Operator.EQ, owner).compare(SearchableFields.RESOURCE_ID, Operator.EQ, resourceId).compare(SearchableFields.REQUESTER, Operator.EQ, requester);
if (scopeId != null) {
mcb = mcb.compare(SearchableFields.SCOPE_ID, Operator.EQ, scopeId);
}
if (tx.getCount(withCriteria(mcb)) > 0) {
throw new ModelDuplicateException("Permission ticket for resource server: '" + resourceServer.getId() + ", Resource: " + resourceId + ", owner: " + owner + ", scopeId: " + scopeId + " already exists.");
}
MapPermissionTicketEntity entity = new MapPermissionTicketEntityImpl();
entity.setResourceId(resourceId);
entity.setRequester(requester);
entity.setCreatedTimestamp(System.currentTimeMillis());
if (scopeId != null) {
entity.setScopeId(scopeId);
}
entity.setOwner(owner);
entity.setResourceServerId(resourceServer.getId());
entity = tx.create(entity);
return entityToAdapter(entity);
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class UsersResource method createUser.
/**
* Create a new user
*
* Username must be unique.
*
* @param rep
* @return
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(final UserRepresentation rep) {
// first check if user has manage rights
try {
auth.users().requireManage();
} catch (ForbiddenException exception) {
if (!canCreateGroupMembers(rep)) {
throw exception;
}
}
String username = rep.getUsername();
if (realm.isRegistrationEmailAsUsername()) {
username = rep.getEmail();
}
if (ObjectUtil.isBlank(username)) {
return 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");
}
if (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed()) {
try {
if (session.users().getUserByEmail(realm, rep.getEmail()) != null) {
return ErrorResponse.exists("User exists with same email");
}
} catch (ModelDuplicateException e) {
return ErrorResponse.exists("User exists with same email");
}
}
UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
UserProfile profile = profileProvider.create(USER_API, rep.toAttributes());
try {
Response response = UserResource.validateUserProfile(profile, null, session);
if (response != null) {
return response;
}
UserModel user = profile.create();
UserResource.updateUserFromRep(profile, user, rep, session, false);
RepresentationToModel.createFederatedIdentities(rep, session, realm, user);
RepresentationToModel.createGroups(rep, realm, user);
RepresentationToModel.createCredentials(rep, session, realm, user, true);
adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), user.getId()).representation(rep).success();
if (session.getTransactionManager().isActive()) {
session.getTransactionManager().commit();
}
return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(user.getId()).build()).build();
} catch (ModelDuplicateException e) {
if (session.getTransactionManager().isActive()) {
session.getTransactionManager().setRollbackOnly();
}
return 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);
} 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);
}
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class AbstractClientRegistrationProvider method create.
public ClientRepresentation create(ClientRegistrationContext context) {
ClientRepresentation client = context.getClient();
event.event(EventType.CLIENT_REGISTER);
RegistrationAuth registrationAuth = auth.requireCreate(context);
try {
RealmModel realm = session.getContext().getRealm();
ClientModel clientModel = ClientManager.createClient(session, realm, client);
if (client.getDefaultRoles() != null) {
for (String name : client.getDefaultRoles()) {
clientModel.addDefaultRole(name);
}
}
if (clientModel.isServiceAccountsEnabled()) {
new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
}
if (Boolean.TRUE.equals(client.getAuthorizationServicesEnabled())) {
RepresentationToModel.createResourceServer(clientModel, session, true);
}
session.clientPolicy().triggerOnEvent(new DynamicClientRegisteredContext(context, clientModel, auth.getJwt(), realm));
ClientRegistrationPolicyManager.triggerAfterRegister(context, registrationAuth, clientModel);
client = ModelToRepresentation.toRepresentation(clientModel, session);
client.setSecret(clientModel.getSecret());
String registrationAccessToken = ClientRegistrationTokenUtils.updateRegistrationAccessToken(session, clientModel, registrationAuth);
client.setRegistrationAccessToken(registrationAccessToken);
if (auth.isInitialAccessToken()) {
ClientInitialAccessModel initialAccessModel = auth.getInitialAccessModel();
session.realms().decreaseRemainingCount(realm, initialAccessModel);
}
client.setDirectAccessGrantsEnabled(false);
Stream<String> defaultRolesNames = clientModel.getDefaultRolesStream();
if (defaultRolesNames != null) {
client.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
}
event.client(client.getClientId()).success();
return client;
} catch (ModelDuplicateException e) {
throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier in use", Response.Status.BAD_REQUEST);
} catch (ClientPolicyException cpe) {
throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class JpaRealmProvider method addRealmRole.
@Override
public RoleModel addRealmRole(RealmModel realm, String id, String name) {
if (getRealmRole(realm, name) != null) {
throw new ModelDuplicateException();
}
RoleEntity entity = new RoleEntity();
entity.setId(id);
entity.setName(name);
entity.setRealmId(realm.getId());
em.persist(entity);
em.flush();
RoleAdapter adapter = new RoleAdapter(session, realm, em, entity);
return adapter;
}
use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.
the class ClientAdapter method addProtocolMapper.
@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
}
String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
ProtocolMapperEntity entity = new ProtocolMapperEntity();
entity.setId(id);
entity.setName(model.getName());
entity.setProtocol(model.getProtocol());
entity.setProtocolMapper(model.getProtocolMapper());
entity.setClient(this.entity);
entity.setConfig(model.getConfig());
em.persist(entity);
this.entity.getProtocolMappers().add(entity);
return entityToModel(entity);
}
Aggregations