use of eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto in project CzechIdMng by bcvsolutions.
the class IdentitySyncTest method testSynchronizationCache.
@Test
public void testSynchronizationCache() {
SysSystemDto system = initData();
SysSyncIdentityConfigDto config = doCreateSyncConfig(system);
IdmRoleDto defaultRole = helper.createRole();
// Set default role to sync configuration
config.setDefaultRole(defaultRole.getId());
config = (SysSyncIdentityConfigDto) syncConfigService.save(config);
this.getBean().deleteAllResourceData();
String testLastName = "test-last-name-same-" + System.currentTimeMillis();
String testFirstName = "test-first-name";
String userOne = "test-1-" + System.currentTimeMillis();
this.getBean().setTestData(userOne, testFirstName, testLastName);
String userTwo = "test-2-" + System.currentTimeMillis();
this.getBean().setTestData(userTwo, testFirstName, testLastName);
SysSystemMappingFilter mappingFilter = new SysSystemMappingFilter();
mappingFilter.setEntityType(SystemEntityType.IDENTITY);
mappingFilter.setSystemId(system.getId());
mappingFilter.setOperationType(SystemOperationType.SYNCHRONIZATION);
List<SysSystemMappingDto> mappings = systemMappingService.find(mappingFilter, null).getContent();
Assert.assertEquals(1, mappings.size());
SysSystemMappingDto defaultMapping = mappings.get(0);
SysSystemAttributeMappingFilter attributeMappingFilter = new SysSystemAttributeMappingFilter();
attributeMappingFilter.setSystemMappingId(defaultMapping.getId());
List<SysSystemAttributeMappingDto> attributes = schemaAttributeMappingService.find(attributeMappingFilter, null).getContent();
SysSystemAttributeMappingDto firstNameAttribute = attributes.stream().filter(attribute -> {
return attribute.getIdmPropertyName().equals(IdmIdentity_.firstName.getName());
}).findFirst().orElse(null);
Assert.assertNotNull(firstNameAttribute);
StringBuilder scriptGenerateUuid = new StringBuilder();
scriptGenerateUuid.append("import java.util.UUID;");
scriptGenerateUuid.append(System.lineSeparator());
scriptGenerateUuid.append("return UUID.randomUUID();");
String scriptName = "generateUuid";
IdmScriptDto scriptUuid = new IdmScriptDto();
scriptUuid.setCategory(IdmScriptCategory.TRANSFORM_FROM);
scriptUuid.setCode(scriptName);
scriptUuid.setName(scriptName);
scriptUuid.setScript(scriptGenerateUuid.toString());
scriptUuid = scriptService.save(scriptUuid);
IdmScriptAuthorityDto scriptAuth = new IdmScriptAuthorityDto();
scriptAuth.setClassName("java.util.UUID");
scriptAuth.setType(ScriptAuthorityType.CLASS_NAME);
scriptAuth.setScript(scriptUuid.getId());
scriptAuth = scriptAuthrotityService.save(scriptAuth);
// we must call script
StringBuilder transformationScript = new StringBuilder();
transformationScript.append("return scriptEvaluator.evaluate(");
transformationScript.append(System.lineSeparator());
transformationScript.append("scriptEvaluator.newBuilder()");
transformationScript.append(System.lineSeparator());
transformationScript.append(".setScriptCode('" + scriptName + "')");
transformationScript.append(System.lineSeparator());
transformationScript.append(".build());");
transformationScript.append(System.lineSeparator());
firstNameAttribute.setTransformFromResourceScript(transformationScript.toString());
firstNameAttribute.setCached(true);
firstNameAttribute = schemaAttributeMappingService.save(firstNameAttribute);
synchornizationService.setSynchronizationConfigId(config.getId());
synchornizationService.process();
SysSyncLogDto log = checkSyncLog(config, SynchronizationActionType.CREATE_ENTITY, 2, OperationResultType.WARNING);
Assert.assertFalse(log.isRunning());
Assert.assertFalse(log.isContainsError());
IdmIdentityFilter filter = new IdmIdentityFilter();
filter.setLastName(testLastName);
List<IdmIdentityDto> identities = identityService.find(filter, null).getContent();
assertEquals(2, identities.size());
//
IdmIdentityDto identityOne = identities.get(0);
IdmIdentityDto identityTwo = identities.get(1);
//
assertNotEquals(identityOne.getFirstName(), identityTwo.getFirstName());
}
use of eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto in project CzechIdMng by bcvsolutions.
the class IdentitySyncTest method createMapping.
private void createMapping(SysSystemDto system, final SysSystemMappingDto entityHandlingResult) {
SysSchemaAttributeFilter schemaAttributeFilter = new SysSchemaAttributeFilter();
schemaAttributeFilter.setSystemId(system.getId());
Page<SysSchemaAttributeDto> schemaAttributesPage = schemaAttributeService.find(schemaAttributeFilter, null);
schemaAttributesPage.forEach(schemaAttr -> {
if (ATTRIBUTE_NAME.equals(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMapping = new SysSystemAttributeMappingDto();
attributeMapping.setUid(true);
attributeMapping.setEntityAttribute(true);
attributeMapping.setIdmPropertyName("username");
attributeMapping.setName(schemaAttr.getName());
attributeMapping.setSchemaAttribute(schemaAttr.getId());
attributeMapping.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMapping);
} else if ("firstname".equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMapping = new SysSystemAttributeMappingDto();
attributeMapping.setIdmPropertyName("firstName");
attributeMapping.setSchemaAttribute(schemaAttr.getId());
attributeMapping.setName(schemaAttr.getName());
attributeMapping.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMapping);
} else if ("lastname".equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMapping = new SysSystemAttributeMappingDto();
attributeMapping.setIdmPropertyName("lastName");
attributeMapping.setName(schemaAttr.getName());
attributeMapping.setSchemaAttribute(schemaAttr.getId());
attributeMapping.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMapping);
} else if (ATTRIBUTE_EMAIL.equalsIgnoreCase(schemaAttr.getName())) {
SysSystemAttributeMappingDto attributeMapping = new SysSystemAttributeMappingDto();
attributeMapping.setIdmPropertyName("email");
attributeMapping.setName(schemaAttr.getName());
attributeMapping.setSchemaAttribute(schemaAttr.getId());
attributeMapping.setSystemMapping(entityHandlingResult.getId());
schemaAttributeMappingService.save(attributeMapping);
}
});
}
use of eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto in project CzechIdMng by bcvsolutions.
the class DefaultAccAuthenticator method authenticate.
@Override
public LoginDto authenticate(LoginDto loginDto) {
// temporary solution for get system id, this is not nice.
String systemCodeable = configurationService.getValue(PROPERTY_AUTH_SYSTEM_ID);
if (StringUtils.isEmpty(systemCodeable)) {
// without system can't check
return null;
}
//
SysSystemDto system = (SysSystemDto) lookupService.lookupDto(SysSystemDto.class, systemCodeable);
//
if (system == null) {
LOG.warn("System by codeable identifier [{}] not found. Check configuration property [{}]", systemCodeable, PROPERTY_AUTH_SYSTEM_ID);
// system doesn't exist
return null;
}
IdmIdentityDto identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, loginDto.getUsername());
if (identity == null) {
throw new IdmAuthenticationException(MessageFormat.format("Check identity can login: The identity [{0}] either doesn't exist or is deleted.", loginDto.getUsername()));
}
//
// search authentication attribute for system with provisioning mapping, only for identity
SysSystemAttributeMappingDto attribute = systemAttributeMappingService.getAuthenticationAttribute(system.getId(), SystemEntityType.IDENTITY);
//
if (attribute == null) {
// attribute MUST exist
throw new ResultCodeException(AccResultCode.AUTHENTICATION_AUTHENTICATION_ATTRIBUTE_DONT_SET, ImmutableMap.of("name", system.getName()));
}
//
// find if identity has account on system
List<AccAccountDto> accounts = accountService.getAccounts(system.getId(), identity.getId());
if (accounts.isEmpty()) {
// user hasn't account on system, continue
return null;
}
//
ResultCodeException authFailedException = null;
IcUidAttribute auth = null;
for (AccAccountDto account : accounts) {
SysSchemaAttributeDto schemaAttribute = schemaAttributeService.get(attribute.getSchemaAttribute());
SysSchemaObjectClassDto schemaObjectClassDto = DtoUtils.getEmbedded(schemaAttribute, SysSchemaAttribute_.objectClass, SysSchemaObjectClassDto.class);
SysSystemEntityDto systemEntityDto = systemEntityService.get(account.getSystemEntity());
IcObjectClass objectClass = new IcObjectClassImpl(schemaObjectClassDto.getObjectClassName());
IcConnectorObject connectorObject = systemService.readConnectorObject(system.getId(), systemEntityDto.getUid(), objectClass);
//
if (connectorObject == null) {
continue;
}
//
String transformUsername = null;
// iterate over all attributes to find authentication attribute
for (IcAttribute icAttribute : connectorObject.getAttributes()) {
if (icAttribute.getName().equals(schemaAttributeService.get(attribute.getSchemaAttribute()).getName())) {
transformUsername = String.valueOf(icAttribute.getValue());
break;
}
}
if (transformUsername == null) {
throw new ResultCodeException(AccResultCode.AUTHENTICATION_USERNAME_DONT_EXISTS, ImmutableMap.of("username", loginDto.getUsername(), "name", system.getName()));
}
// authentication over system, when password or username not exist or bad credentials - throw error
try {
// authentication against system
auth = provisioningService.authenticate(transformUsername, loginDto.getPassword(), system, SystemEntityType.IDENTITY);
authFailedException = null;
// check auth
if (auth == null || auth.getValue() == null) {
authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername()));
// failed, continue to another
break;
}
// everything success break
break;
} catch (ResultCodeException e) {
// failed, continue to another
authFailedException = new ResultCodeException(CoreResultCode.AUTH_FAILED, "Invalid login or password.", e);
}
}
if (auth == null || auth.getValue() == null) {
authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername()));
}
//
if (authFailedException != null) {
throw authFailedException;
}
String module = this.getModule();
loginDto = jwtAuthenticationService.createJwtAuthenticationAndAuthenticate(loginDto, identity, module);
LOG.info("Identity with username [{}] is authenticated by system [{}]", loginDto.getUsername(), system.getName());
return loginDto;
}
use of eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto in project CzechIdMng by bcvsolutions.
the class AbstractProvisioningExecutor method compileAtributeForStrategy.
/**
* Compile given attribute for strategy
*
* @param strategy
* @param defaultAttribute
* @param overloadingAttributes
* @return
*/
protected List<AttributeMapping> compileAtributeForStrategy(AttributeMappingStrategyType strategy, AttributeMapping defaultAttribute, List<SysRoleSystemAttributeDto> overloadingAttributes) {
List<AttributeMapping> finalAttributes = new ArrayList<>();
List<SysRoleSystemAttributeDto> attributesOrdered = overloadingAttributes.stream().filter(roleSystemAttribute -> {
// Search attribute override same schema attribute
SysSystemAttributeMappingDto attributeMapping = systemAttributeMappingService.get(roleSystemAttribute.getSystemAttributeMapping());
return attributeMapping.equals(defaultAttribute);
}).sorted((att1, att2) -> {
// Sort attributes by role priority
SysRoleSystemDto roleSystem2 = roleSystemService.get(att2.getRoleSystem());
SysRoleSystemDto roleSystem1 = roleSystemService.get(att1.getRoleSystem());
IdmRoleDto role1 = roleService.get(roleSystem1.getRole());
IdmRoleDto role2 = roleService.get(roleSystem2.getRole());
return Integer.valueOf(role2.getPriority()).compareTo(Integer.valueOf(role1.getPriority()));
}).collect(Collectors.toList());
// We have some overloaded attributes
if (!attributesOrdered.isEmpty()) {
List<SysRoleSystemAttributeDto> attributesOrderedGivenStrategy = attributesOrdered.stream().filter(attribute -> {
return strategy == attribute.getStrategyType();
}).collect(Collectors.toList());
// We do not have overloaded attributes for given strategy
if (attributesOrderedGivenStrategy.isEmpty()) {
return finalAttributes;
}
// First element have role with max priority
SysRoleSystemDto roleSystemForSetMaxPriority = roleSystemService.get(attributesOrderedGivenStrategy.get(0).getRoleSystem());
IdmRoleDto roleForSetMaxPriority = roleService.get(roleSystemForSetMaxPriority.getRole());
int maxPriority = roleForSetMaxPriority.getPriority();
// We will search for attribute with highest priority (and role
// name)
Optional<SysRoleSystemAttributeDto> highestPriorityAttributeOptional = attributesOrderedGivenStrategy.stream().filter(attribute -> {
SysRoleSystemDto roleSystem = roleSystemService.get(attribute.getRoleSystem());
IdmRoleDto roleDto = roleService.get(roleSystem.getRole());
// Filter attributes by max priority
return maxPriority == roleDto.getPriority();
}).sorted((att1, att2) -> {
// Second filtering, if we have same priority, then
// we will sort by role name
SysRoleSystemDto roleSystem1 = roleSystemService.get(att1.getRoleSystem());
SysRoleSystemDto roleSystem2 = roleSystemService.get(att2.getRoleSystem());
//
IdmRoleDto roleDto1 = roleService.get(roleSystem1.getRole());
IdmRoleDto roleDto2 = roleService.get(roleSystem2.getRole());
//
return roleDto2.getName().compareTo(roleDto1.getName());
}).findFirst();
if (highestPriorityAttributeOptional.isPresent()) {
SysRoleSystemAttributeDto highestPriorityAttribute = highestPriorityAttributeOptional.get();
// overloaded attributes
if (strategy == AttributeMappingStrategyType.AUTHORITATIVE_MERGE || strategy == AttributeMappingStrategyType.MERGE) {
attributesOrderedGivenStrategy.forEach(attribute -> {
// Disabled attribute will be skipped
if (!attribute.isDisabledDefaultAttribute()) {
// Default values (values from schema attribute
// handling)
attribute.setSchemaAttribute(defaultAttribute.getSchemaAttribute());
attribute.setTransformFromResourceScript(defaultAttribute.getTransformFromResourceScript());
// Common properties (for MERGE strategy) will be
// set from MERGE attribute with highest priority
attribute.setSendAlways(highestPriorityAttribute.isSendAlways());
attribute.setSendOnlyIfNotNull(highestPriorityAttribute.isSendOnlyIfNotNull());
// Add modified attribute to final list
finalAttributes.add(attribute);
}
});
return finalAttributes;
}
// We will search for disabled overloaded attribute
Optional<SysRoleSystemAttributeDto> disabledOverloadedAttOptional = attributesOrderedGivenStrategy.stream().filter(attribute -> {
// Filter attributes by max priority
SysRoleSystemDto roleSystem = roleSystemService.get(attribute.getRoleSystem());
IdmRoleDto roleDto = roleService.get(roleSystem.getRole());
return maxPriority == roleDto.getPriority();
}).filter(attribute -> {
// overloaded attribute
return attribute.isDisabledDefaultAttribute();
}).findFirst();
if (disabledOverloadedAttOptional.isPresent()) {
// priority
return finalAttributes;
}
// Disabled attribute will be skipped
if (!highestPriorityAttribute.isDisabledDefaultAttribute()) {
// Default values (values from schema attribute handling)
highestPriorityAttribute.setSchemaAttribute(defaultAttribute.getSchemaAttribute());
highestPriorityAttribute.setCached(defaultAttribute.isCached());
highestPriorityAttribute.setTransformFromResourceScript(defaultAttribute.getTransformFromResourceScript());
// Add modified attribute to final list
finalAttributes.add(highestPriorityAttribute);
return finalAttributes;
}
}
}
if (!defaultAttribute.isDisabledAttribute() && strategy == defaultAttribute.getStrategyType()) {
finalAttributes.add(defaultAttribute);
}
return finalAttributes;
}
use of eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto in project CzechIdMng by bcvsolutions.
the class AbstractSynchronizationExecutor method updateExtendedAttributes.
/**
* Update extended attribute for given entity. Entity must be persisted first.
*
* @param mappedAttributes
* @param uid
* @param icAttributes
* @param entity
* @param create
* (is create or update entity situation)
* @param context
* @return
*/
@SuppressWarnings("unchecked")
protected DTO updateExtendedAttributes(List<SysSystemAttributeMappingDto> mappedAttributes, String uid, List<IcAttribute> icAttributes, DTO dto, boolean create, SynchronizationContext context) {
mappedAttributes.stream().filter(attribute -> {
// Skip disabled attributes
// Only for extended attributes
boolean fastResult = !attribute.isDisabledAttribute() && attribute.isExtendedAttribute();
if (!fastResult) {
return false;
}
// Can be value set by attribute strategy?
return this.canSetValue(uid, attribute, dto, create);
}).forEach(attribute -> {
String attributeProperty = attribute.getIdmPropertyName();
Object transformedValue = getValueByMappedAttribute(attribute, icAttributes, context);
// Save to extended attribute
if (!formService.isFormable(dto.getClass())) {
String message = MessageFormat.format("Entity [{0}] is not instance of fromable entity!", dto.getId());
throw new ProvisioningException(AccResultCode.SYNCHRONIZATION_ERROR_DURING_SYNC_ITEM, ImmutableMap.of("uid", uid, "message", message));
}
IdmFormAttributeDto defAttribute = formService.getDefinition(dto.getClass()).getMappedAttributeByCode(attributeProperty);
if (defAttribute == null) {
// eav definition could be changed
String message = MessageFormat.format("Form attribute defininion [{0}] was not found!", attributeProperty);
throw new ProvisioningException(AccResultCode.SYNCHRONIZATION_ERROR_DURING_SYNC_ITEM, ImmutableMap.of("uid", uid, "message", message));
}
if (transformedValue instanceof List<?>) {
((List<?>) transformedValue).stream().forEach(value -> {
if (value != null && !(value instanceof Serializable)) {
String message = MessageFormat.format("Value is not serializable [{0}] for attribute [{1}] and UID [{2}]!", value, attribute, uid);
throw new ProvisioningException(AccResultCode.SYNCHRONIZATION_ERROR_DURING_SYNC_ITEM, ImmutableMap.of("uid", uid, "message", message));
}
});
formService.saveValues(dto, defAttribute, (List<Serializable>) transformedValue);
} else {
formService.saveValues(dto, defAttribute, Lists.newArrayList((Serializable) transformedValue));
}
});
return dto;
}
Aggregations