use of eu.bcvsolutions.idm.core.api.exception.CoreException in project CzechIdMng by bcvsolutions.
the class AdUserConnectorType method executeStepOne.
/**
* Execute first step of AD wizard.
*/
protected void executeStepOne(ConnectorTypeDto connectorType) {
String port = connectorType.getMetadata().get(PORT);
Assert.notNull(port, "Port cannot be null!");
String host = connectorType.getMetadata().get(HOST);
Assert.notNull(host, "Host cannot be null!");
String user = connectorType.getMetadata().get(USER);
Assert.notNull(user, "Username cannot be null!");
String sslSwitch = connectorType.getMetadata().get(SSL_SWITCH);
Assert.notNull(sslSwitch, "SSL switch cannot be null!");
String password = connectorType.getMetadata().get(PASSWORD);
String systemId = connectorType.getMetadata().get(SYSTEM_DTO_KEY);
SysSystemDto systemDto;
boolean create = true;
if (systemId != null) {
// System already exists.
create = false;
systemDto = getSystemService().get(UUID.fromString(systemId), IdmBasePermission.READ);
} else {
// Create new system.
systemDto = new SysSystemDto();
// System is set as readOnly only if is new.
systemDto.setReadonly(true);
}
systemDto.setName(connectorType.getMetadata().get(SYSTEM_NAME));
// Resolve remote system.
systemDto.setRemoteServer(connectorType.getRemoteServer());
// Find connector key and set it to the system.
IcConnectorKey connectorKey = getConnectorManager().findConnectorKey(connectorType);
Assert.notNull(connectorKey, "Connector key was not found!");
systemDto.setConnectorKey(new SysConnectorKeyDto(connectorKey));
// Check permission on create or update system (others permissions will be not checked (EAV for identity, mapping, sync, entity state ...)).
systemDto = getSystemService().save(systemDto, create ? IdmBasePermission.CREATE : IdmBasePermission.UPDATE);
// Put new system to the connector type (will be returned to FE).
connectorType.getEmbedded().put(SYSTEM_DTO_KEY, systemDto);
connectorType.getMetadata().put(SYSTEM_DTO_KEY, systemDto.getId().toString());
IdmFormDefinitionDto connectorFormDef = this.getSystemService().getConnectorFormDefinition(systemDto);
// Set the port.
this.setValueToConnectorInstance(PORT, port, systemDto, connectorFormDef);
// Set the host.
this.setValueToConnectorInstance(HOST, host, systemDto, connectorFormDef);
// Set the user.
this.setValueToConnectorInstance(PRINCIPAL, user, systemDto, connectorFormDef);
// Set the SSL switch.
this.setValueToConnectorInstance(SSL, sslSwitch, systemDto, connectorFormDef);
// Set the password.
// Password is mandatory only if none exists in connector configuration.
String passwordInSystem = this.getValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef);
if (Strings.isNotBlank(password) && !GuardedString.SECRED_PROXY_STRING.equals(password)) {
this.setValueToConnectorInstance(CREDENTIALS, password, systemDto, connectorFormDef);
} else {
Assert.notNull(passwordInSystem, "Password cannot be null!");
// Load from confidential storage.
password = getConfidentialValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef);
}
// Find domain DN.
if (Strings.isBlank(connectorType.getMetadata().get(DOMAIN_KEY))) {
String defaultNamingContext = this.findDnsHostName("389", host, user, password, false);
connectorType.getMetadata().put(DOMAIN_KEY, defaultNamingContext);
}
// Find Users container DN.
String usersContainerDN = this.findDn("(&(CN=Users)(objectClass=container))", "389", host, user, password, false);
connectorType.getMetadata().put(TEST_USER_CONTAINER_KEY, usersContainerDN);
// Find Domain Users group DN.
String domainUsersDN = this.findDn("(&(CN=Domain Guests)(objectClass=group))", "389", host, user, password, false);
connectorType.getMetadata().put(TEST_GROUP_KEY, domainUsersDN);
// Generate random test user name.
connectorType.getMetadata().put(TEST_USERNAME_KEY, MessageFormat.format("TestUserIdM_{0}", UUID.randomUUID().toString().substring(0, 8)));
if (!Boolean.parseBoolean(sslSwitch)) {
// LDAPS is trun off, this step will be skipped.
return;
}
Pair<X509Certificate, Boolean> serverCertificatePair = getServerCertificate(port, host);
if (serverCertificatePair != null) {
boolean hasTrustedCA = serverCertificatePair.getValue();
// Put information if the server already has trusted certificate.
connectorType.getMetadata().put(HAS_TRUSTED_CA_KEY, String.valueOf(hasTrustedCA));
X509Certificate serverCertificate = serverCertificatePair.getKey();
X509Certificate resultCertificate = getCertificateFromAD(serverCertificate, port, host, user, password);
if (resultCertificate != null) {
try {
// Save CA as file.
File caFile = new File(Paths.get(getTrustedCaFolder(), getCaFileName(resultCertificate)).toString());
FileUtils.copyInputStreamToFile(CertificateUtils.certificateToPem(resultCertificate), caFile);
// Save certificate as a temporary attachment.
IdmAttachmentDto attachment = new IdmAttachmentDto();
attachment.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE);
attachment.setName("AD_CA");
attachment.setMimetype("application/x-pem-file");
attachment.setInputData(CertificateUtils.certificateToPem(resultCertificate));
attachment = attachmentManager.saveAttachment(null, attachment);
// Save server certificate as a temporary attachment.
IdmAttachmentDto serverAttachment = new IdmAttachmentDto();
serverAttachment.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE);
serverAttachment.setName("SERVER_AD_CA");
serverAttachment.setMimetype("application/x-pem-file");
serverAttachment.setInputData(CertificateUtils.certificateToPem(serverCertificate));
serverAttachment = attachmentManager.saveAttachment(null, serverAttachment);
// Put data to connectorType for FE
connectorType.getMetadata().put(CRT_ATTACHMENT_ID_KEY, attachment.getId().toString());
connectorType.getMetadata().put(CRT_SUBJECT_DN_KEY, resultCertificate.getSubjectDN().getName());
connectorType.getMetadata().put(CRT_VALIDITY_FROM_KEY, getZonedDateTime(resultCertificate.getNotBefore()));
connectorType.getMetadata().put(CRT_VALIDITY_TILL_KEY, getZonedDateTime(resultCertificate.getNotAfter()));
// Fingerprint by SHA1 (is use in windows certificate manager)
connectorType.getMetadata().put(CRT_FINGER_PRINT_KEY, DigestUtils.sha1Hex(resultCertificate.getEncoded()));
connectorType.getMetadata().put(CRT_FILE_PATH_KEY, Paths.get(caFile.getAbsolutePath()).toString());
// Put data to connectorType for FE
connectorType.getMetadata().put(SERVER_CRT_ATTACHMENT_ID_KEY, serverAttachment.getId().toString());
connectorType.getMetadata().put(SERVER_CRT_SUBJECT_DN_KEY, serverCertificate.getSubjectDN().getName());
connectorType.getMetadata().put(SERVER_CRT_VALIDITY_FROM_KEY, getZonedDateTime(serverCertificate.getNotBefore()));
connectorType.getMetadata().put(SERVER_CRT_VALIDITY_TILL_KEY, getZonedDateTime(serverCertificate.getNotAfter()));
// Fingerprint by SHA1 (is use in windows certificate manager)
connectorType.getMetadata().put(SERVER_CRT_FINGER_PRINT_KEY, DigestUtils.sha1Hex(serverCertificate.getEncoded()));
} catch (CertificateException | IOException ex) {
throw new CoreException(ex.getLocalizedMessage(), ex);
}
}
}
}
use of eu.bcvsolutions.idm.core.api.exception.CoreException in project CzechIdMng by bcvsolutions.
the class AbstractSchedulableTaskExecutor method execute.
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
if (this.isDisabled()) {
LOG.warn("Task [{}] is disabled and cannot be executed, remove schedule for this task to hide this warning.", AutowireHelper.getTargetClass(this).getSimpleName());
//
return;
}
String executionDateProperty = context.getMergedJobDataMap().getString(EntityEvent.EVENT_PROPERTY_EXECUTE_DATE);
if (StringUtils.isNotBlank(executionDateProperty)) {
ZonedDateTime executionDate = ZonedDateTime.parse(executionDateProperty);
// Is it safe to ask about now and count with delay after task execution?
if (ZonedDateTime.now().isBefore(executionDate)) {
LOG.debug("Task [{}] first fire time will be executed after [{}].", AutowireHelper.getTargetClass(this).getSimpleName(), executionDateProperty);
//
return;
}
}
// run as system - called from scheduler internall
if (securityService.isAuthenticated() && !securityService.isSystemAuthenticated()) {
throw new CoreException("System want to reuse thread logged with identity [" + securityService.getCurrentUsername() + "] for system processing!");
}
securityService.setSystemAuthentication();
//
// scheduled task is quartz reference to IdM entity
IdmScheduledTaskDto taskDto = getScheduledTask(context);
//
// add task to queue only - quartz will start take care of the rest
createIdmLongRunningTask(context, taskDto);
}
use of eu.bcvsolutions.idm.core.api.exception.CoreException in project CzechIdMng by bcvsolutions.
the class DefaultRequestManager method findPotencialParents.
/**
* Find potential parents. Invokes all method with UUID return type and without
* input parameters.
*
* @param filter
* @return
*/
private List<RequestPredicate> findPotencialParents(BaseFilter filter) {
Assert.notNull(filter, "Filter is mandatory!");
List<MethodDescriptor> descriptors;
try {
descriptors = //
Lists.newArrayList(Introspector.getBeanInfo(filter.getClass()).getMethodDescriptors()).stream().filter(//
methodDescriptor -> UUID.class.equals(methodDescriptor.getMethod().getReturnType())).filter(methodDescriptor -> methodDescriptor.getMethod().getParameterTypes() == null || //
methodDescriptor.getMethod().getParameterTypes().length == 0).collect(Collectors.toList());
} catch (IntrospectionException e) {
throw new CoreException(e);
}
//
List<RequestPredicate> results = new ArrayList<>();
descriptors.stream().forEach(descriptor -> {
try {
Object value = descriptor.getMethod().invoke(filter, new Object[] {});
if (value == null) {
return;
}
RequestFilterPredicate filterPredicate = descriptor.getMethod().getAnnotation(RequestFilterPredicate.class);
results.add(new RequestPredicate((UUID) value, filterPredicate != null ? filterPredicate.field() : null));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new CoreException(e);
}
});
return results;
}
use of eu.bcvsolutions.idm.core.api.exception.CoreException in project CzechIdMng by bcvsolutions.
the class DefaultRequestManager method startRequest.
@Override
@Transactional
public IdmRequestDto startRequest(UUID requestId, boolean checkRight) {
IdmRequestDto request = requestService.get(requestId);
Assert.notNull(request, "Request is required!");
try {
RequestManager service = this.getRequestManager();
if (!(service instanceof DefaultRequestManager)) {
throw new CoreException("We expects instace of DefaultRequestManager!");
}
return ((DefaultRequestManager) service).startRequestNewTransactional(requestId, checkRight);
} catch (Exception ex) {
LOG.error(ex.getLocalizedMessage(), ex);
request = requestService.get(requestId);
Throwable exceptionToLog = ExceptionUtils.resolveException(ex);
if (exceptionToLog instanceof ResultCodeException) {
//
request.setResult(new //
OperationResultDto.Builder(//
OperationState.EXCEPTION).setException(//
(ResultCodeException) exceptionToLog).build());
} else {
//
request.setResult(new //
OperationResultDto.Builder(//
OperationState.EXCEPTION).setCause(//
exceptionToLog).build());
}
request.setState(RequestState.EXCEPTION);
return requestService.save(request);
}
}
use of eu.bcvsolutions.idm.core.api.exception.CoreException in project CzechIdMng by bcvsolutions.
the class DefaultRequestManager method getChanges.
@SuppressWarnings("unchecked")
@Override
public IdmRequestItemChangesDto getChanges(IdmRequestItemDto item, BasePermission... permission) {
LOG.debug(MessageFormat.format("Start read request item with changes [{0}].", item));
Assert.notNull(item, "Idm request item cannot be null!");
if (Strings.isNullOrEmpty(item.getOwnerType()) || item.getOwnerId() == null) {
return null;
}
Class<? extends Requestable> dtoClass;
try {
dtoClass = (Class<? extends Requestable>) Class.forName(item.getOwnerType());
} catch (ClassNotFoundException e) {
throw new CoreException(e);
}
ReadDtoService<?, ?> readService = getServiceByItem(item, dtoClass);
Requestable currentDto = (Requestable) readService.get(item.getOwnerId(), permission);
if (currentDto == null) {
try {
currentDto = (Requestable) dtoClass.getDeclaredConstructor().newInstance();
currentDto.setId(item.getOwnerId());
} catch (ReflectiveOperationException e) {
throw new CoreException(e);
}
}
Requestable changedDto = this.get(item.getRequest(), currentDto);
RequestOperationType itemOperation = item.getOperation();
List<IdmRequestItemAttributeDto> resultAttributes = getChanges((AbstractDto) currentDto, (AbstractDto) changedDto, itemOperation);
IdmRequestItemChangesDto result = new IdmRequestItemChangesDto();
result.setRequestItem(item);
result.getAttributes().addAll(resultAttributes);
LOG.debug(MessageFormat.format("End of reading the request item with changes [{0}].", item));
return result;
}
Aggregations