use of eu.bcvsolutions.idm.core.security.api.domain.BasePermission in project CzechIdMng by bcvsolutions.
the class AbstractFormableService method publish.
@Override
@Transactional
public EventContext<DTO> publish(EntityEvent<DTO> event, EntityEvent<?> parentEvent, BasePermission... permission) {
// check access to filled form values
// access has to be evaluated before event is published - is not available in save internal method
BasePermission[] permissions = PermissionUtils.trimNull(permission);
if (!ObjectUtils.isEmpty(permissions)) {
FormableEntity owner = getOwner(event.getContent());
FormValueService<FormableEntity> formValueService = formService.getFormValueService(getDtoClass());
event.getContent().getEavs().forEach(formInstance -> {
formInstance.getValues().forEach(formValue -> {
// set owner is needed for checking access on new values
formValue.setOwner(owner);
Set<String> availablePermissions = formValueService.getPermissions(formValue);
if (event.hasType(CoreEventType.CREATE)) {
// Create or update permission, when owner is created.
if (!PermissionUtils.hasAnyPermission(availablePermissions, IdmBasePermission.CREATE, IdmBasePermission.UPDATE)) {
throw new ForbiddenEntityException(formValue, IdmBasePermission.CREATE, IdmBasePermission.UPDATE);
}
} else {
// UPDATE is enough for all CUD otherwise.
if (!PermissionUtils.hasPermission(availablePermissions, IdmBasePermission.UPDATE)) {
throw new ForbiddenEntityException(formValue, IdmBasePermission.UPDATE);
}
}
});
});
}
//
return super.publish(event, parentEvent, permission);
}
use of eu.bcvsolutions.idm.core.security.api.domain.BasePermission in project CzechIdMng by bcvsolutions.
the class AuthorizationEvaluator method getOrPredicate.
/**
* Returns jpa criteria predicate for given policy and any permissions, which can be used in queries - adds security on entities.
* Predicate with "exist" subquery is recommended.
* Could return {@code null}, if evaluator doesn't want to append a predicate.
*
* @param root evaluated {@link BaseEntity} type root
* @param query
* @param builder
* @param policy
* @param permission permissions to evaluate (OR)
* @return predicate with "exists" subquery is recommended
* @since 11.1.0
*/
default Predicate getOrPredicate(Root<E> root, CriteriaQuery<?> query, CriteriaBuilder builder, AuthorizationPolicy policy, BasePermission... permission) {
Assert.notNull(permission, "Permission is required");
//
// no data by default
final List<Predicate> predicates = Lists.newArrayList();
//
for (BasePermission singlePermission : PermissionUtils.trimNull(permission)) {
Predicate predicate = getPredicate(root, query, builder, policy, singlePermission);
if (predicate != null) {
predicates.add(predicate);
}
}
// predicate will be not applied
if (predicates.isEmpty()) {
return null;
}
if (predicates.size() == 1) {
// or is not needed
return predicates.get(0);
}
//
return builder.or(predicates.toArray(new Predicate[predicates.size()]));
}
use of eu.bcvsolutions.idm.core.security.api.domain.BasePermission in project CzechIdMng by bcvsolutions.
the class IdentityRoleByIdentityDeduplicationBulkAction method getDuplicatesIdentityRoleForContract.
/**
* Method return duplicities for {@link IdmIdentityContractDto}
* @param contract
* @return
*/
public List<IdmIdentityRoleDto> getDuplicatesIdentityRoleForContract(IdmIdentityContractDto contract) {
boolean checkSubdefinition = isCheckSubdefinition();
// Get all identity roles
IdmIdentityRoleFilter identityRoleFilter = new IdmIdentityRoleFilter();
identityRoleFilter.setIdentityId(contract.getIdentity());
identityRoleFilter.setIdentityContractId(contract.getId());
// Identity roles must be sorted by create, for duplicities with manually will be removed always the newer.
List<IdmIdentityRoleDto> identityRoles = identityRoleService.find(identityRoleFilter, PageRequest.of(0, Integer.MAX_VALUE, new Sort(Direction.DESC, IdmIdentityRole_.created.getName())), PermissionUtils.toPermissions(getAuthoritiesForIdentityRole()).toArray(new BasePermission[] {})).getContent();
// load eav instance, if eav values has to be checked
if (checkSubdefinition) {
identityRoles.forEach(identityRole -> {
identityRole.setEavs(Lists.newArrayList(identityRoleService.getRoleAttributeValues(identityRole)));
});
}
// Get map of duplicity roles (roleId, assignedRoles).
Map<UUID, List<IdmIdentityRoleDto>> duplicateRoles = identityRoles.stream().collect(// Group identity roles by role.
Collectors.groupingBy(//
IdmIdentityRoleDto::getRole)).entrySet().stream().filter(// Filter only by values where is more than one record (possible duplicates).
entry -> entry.getValue().size() > 1).collect(//
Collectors.toMap(// Collect as map where key is UUID of role.
k -> k.getKey(), // And value is list of identity roles for this role.
v -> v.getValue()));
//
//
List<IdmIdentityRoleDto> resolvedDuplicities = new ArrayList<>();
// Iterate over duplicated roles. In Key is ID of role that has more finding for the contract.
for (Entry<UUID, List<IdmIdentityRoleDto>> entry : duplicateRoles.entrySet()) {
List<IdmIdentityRoleDto> assignedRoles = entry.getValue();
List<IdmIdentityRoleDto> rolesToCheck = // ~ manually assigned direct roles can be removed only
assignedRoles.stream().filter(idenityRole -> {
// not automatic
return idenityRole.getAutomaticRole() == null;
}).filter(idenityRole -> {
// not sub role
return idenityRole.getDirectRole() == null;
}).collect(Collectors.toList());
if (rolesToCheck.isEmpty()) {
continue;
}
//
for (IdmIdentityRoleDto checkRoleOne : rolesToCheck) {
// skip already processed assigned role
if (resolvedDuplicities.contains(checkRoleOne)) {
continue;
}
//
while (true) {
IdmIdentityRoleDto duplicate = null;
for (Iterator<IdmIdentityRoleDto> i = assignedRoles.iterator(); i.hasNext(); ) {
IdmIdentityRoleDto checkRoleTwo = i.next();
if (Objects.equals(checkRoleOne.getId(), checkRoleTwo.getId())) {
// the same assigned role is not duplicate
continue;
}
//
duplicate = identityRoleService.getDuplicated(checkRoleOne, checkRoleTwo, !checkSubdefinition);
//
if (duplicate != null) {
// add duplicate
if (!resolvedDuplicities.contains(duplicate)) {
resolvedDuplicities.add(duplicate);
}
assignedRoles.remove(duplicate);
// ~ run again, until no duplicate is found
break;
} else {
continue;
}
}
// end => no duplicates was found finally, or duplicate is controlled role itself
if (duplicate == null || duplicate.getId().equals(checkRoleOne.getId())) {
break;
}
}
}
}
//
return resolvedDuplicities;
}
use of eu.bcvsolutions.idm.core.security.api.domain.BasePermission in project CzechIdMng by bcvsolutions.
the class IdentityRoleByIdentityDeduplicationBulkAction method processDto.
@Override
protected OperationResult processDto(IdmIdentityDto identity) {
UUID identityId = identity.getId();
// Result will be list of concepts.
List<IdmConceptRoleRequestDto> concepts = new ArrayList<>();
List<IdmIdentityContractDto> contracts = identityContractService.findAllValidForDate(identityId, LocalDate.now(), null);
for (IdmIdentityContractDto contract : contracts) {
// Check access for contract.
try {
identityContractService.checkAccess(contract, PermissionUtils.toPermissions(getAuthoritiesForIdentityContract()).toArray(new BasePermission[] {}));
} catch (ForbiddenEntityException e) {
continue;
}
// Process deduplication per identity contract.
concepts.addAll(processDuplicitiesForContract(contract));
}
// If result is empty for identity will be removed any roles.
if (concepts.isEmpty()) {
return new OperationResult.Builder(OperationState.EXECUTED).build();
}
IdmRoleRequestDto roleRequest = new IdmRoleRequestDto();
roleRequest.setApplicant(identityId);
roleRequest.setRequestedByType(RoleRequestedByType.MANUALLY);
roleRequest.setLog("Request was created by bulk action (deduplication).");
// if set approve, dont execute immediately
roleRequest.setExecuteImmediately(!isApprove());
roleRequest = roleRequestService.save(roleRequest, IdmBasePermission.CREATE);
for (IdmConceptRoleRequestDto concept : concepts) {
concept.setRoleRequest(roleRequest.getId());
concept = conceptRoleRequestService.save(concept, IdmBasePermission.CREATE);
}
Map<String, Serializable> properties = new HashMap<>();
properties.put(RoleRequestApprovalProcessor.CHECK_RIGHT_PROPERTY, Boolean.TRUE);
RoleRequestEvent event = new RoleRequestEvent(RoleRequestEventType.EXCECUTE, roleRequest, properties);
event.setPriority(PriorityType.HIGH);
IdmRoleRequestDto request = roleRequestService.startRequestInternal(event);
//
if (request.getState() == RoleRequestState.EXECUTED) {
return new OperationResult.Builder(OperationState.EXECUTED).build();
} else {
return new OperationResult.Builder(OperationState.CREATED).build();
}
}
use of eu.bcvsolutions.idm.core.security.api.domain.BasePermission in project CzechIdMng by bcvsolutions.
the class FormValueDeleteBulkAction method getValues.
@SuppressWarnings("rawtypes")
protected List<IdmFormValueDto> getValues(IdmBulkActionDto action, StringBuilder description) {
List<IdmFormValueDto> values = null;
if (!action.getIdentifiers().isEmpty()) {
FormValueService<?> lastUsedFormValueService = null;
values = new ArrayList<IdmFormValueDto>();
for (UUID valueId : action.getIdentifiers()) {
IdmFormValueDto formValue = null;
// we have value identifier only => we need to iterate all registered services ... but we can to cache lastly used - will be same in 99%
// we will not need to check permission manualy in next step.
BasePermission[] permissionForEntity = getPermissionForEntity();
if (lastUsedFormValueService != null) {
formValue = lastUsedFormValueService.get(valueId, permissionForEntity);
}
for (FormValueService<?> formValueService : formService.getAvailableFormValueServices()) {
formValue = formValueService.get(valueId, permissionForEntity);
if (formValue != null) {
lastUsedFormValueService = formValueService;
//
break;
}
}
//
if (formValue != null) {
values.add(formValue);
} else {
// TODO: not found / missing permission ... add operation result some how
LOG.warn("Form value with id [{}] not found, cannot be removed", valueId);
}
}
//
if (description != null) {
description.append(System.lineSeparator());
description.append("For filtering is used list of ID's.");
}
} else if (action.getTransformedFilter() != null) {
// is necessary find entities with given base permission
List<IdmFormValueDto> content = formService.findValues((IdmFormValueFilter) action.getTransformedFilter(), null, getPermissionForEntity()).getContent();
// it is necessary create new arraylist because return list form find is unmodifiable
values = new ArrayList<>(content);
//
if (description != null) {
description.append(System.lineSeparator());
description.append("For filtering is used filter:");
description.append(System.lineSeparator());
String filterAsString = Arrays.toString(action.getFilter().entrySet().toArray());
description.append(filterAsString);
}
} else {
throw new ResultCodeException(CoreResultCode.BULK_ACTION_ENTITIES_ARE_NOT_SPECIFIED);
}
// remove given ids
if (!action.getRemoveIdentifiers().isEmpty()) {
values.removeIf(v -> {
return action.getRemoveIdentifiers().contains(v.getId());
});
}
return values;
}
Aggregations