Search in sources :

Example 1 with BasePermission

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);
}
Also used : IdmBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission) BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) FormableEntity(eu.bcvsolutions.idm.core.eav.api.entity.FormableEntity) ForbiddenEntityException(eu.bcvsolutions.idm.core.api.exception.ForbiddenEntityException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with BasePermission

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()]));
}
Also used : BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) Predicate(javax.persistence.criteria.Predicate)

Example 3 with BasePermission

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;
}
Also used : IdmConceptRoleRequestService(eu.bcvsolutions.idm.core.api.service.IdmConceptRoleRequestService) IdmIdentityRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) Autowired(org.springframework.beans.factory.annotation.Autowired) Enabled(eu.bcvsolutions.idm.core.security.api.domain.Enabled) ForbiddenEntityException(eu.bcvsolutions.idm.core.api.exception.ForbiddenEntityException) IdmRoleRequestService(eu.bcvsolutions.idm.core.api.service.IdmRoleRequestService) CoreGroupPermission(eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission) Map(java.util.Map) BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) Sort(org.springframework.data.domain.Sort) NotificationLevel(eu.bcvsolutions.idm.core.notification.api.domain.NotificationLevel) IdmIdentityContractService(eu.bcvsolutions.idm.core.api.service.IdmIdentityContractService) AbstractBulkAction(eu.bcvsolutions.idm.core.api.bulk.action.AbstractBulkAction) IdmRoleRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleRequestDto) ReadWriteDtoService(eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService) PageRequest(org.springframework.data.domain.PageRequest) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) PriorityType(eu.bcvsolutions.idm.core.api.domain.PriorityType) Serializable(java.io.Serializable) Objects(java.util.Objects) List(java.util.List) PermissionUtils(eu.bcvsolutions.idm.core.security.api.utils.PermissionUtils) LocalDate(java.time.LocalDate) Entry(java.util.Map.Entry) IdmIdentityService(eu.bcvsolutions.idm.core.api.service.IdmIdentityService) RoleRequestEventType(eu.bcvsolutions.idm.core.model.event.RoleRequestEvent.RoleRequestEventType) RoleRequestApprovalProcessor(eu.bcvsolutions.idm.core.model.event.processor.role.RoleRequestApprovalProcessor) IdmIdentityRole_(eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole_) RoleRequestedByType(eu.bcvsolutions.idm.core.api.domain.RoleRequestedByType) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PersistentType(eu.bcvsolutions.idm.core.eav.api.domain.PersistentType) IdmBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission) Lists(com.google.common.collect.Lists) IdmIdentityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter) CoreModuleDescriptor(eu.bcvsolutions.idm.core.CoreModuleDescriptor) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) IdmConceptRoleRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmConceptRoleRequestDto) Direction(org.springframework.data.domain.Sort.Direction) IdmIdentityContractDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto) Description(org.springframework.context.annotation.Description) IdmIdentityRoleService(eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService) Iterator(java.util.Iterator) IdmIdentityRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) RoleRequestState(eu.bcvsolutions.idm.core.api.domain.RoleRequestState) Component(org.springframework.stereotype.Component) RoleRequestEvent(eu.bcvsolutions.idm.core.model.event.RoleRequestEvent) ConceptRoleRequestOperation(eu.bcvsolutions.idm.core.api.domain.ConceptRoleRequestOperation) ArrayList(java.util.ArrayList) Sort(org.springframework.data.domain.Sort) List(java.util.List) ArrayList(java.util.ArrayList) IdmIdentityRoleFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter) IdmIdentityRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto) UUID(java.util.UUID)

Example 4 with BasePermission

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();
    }
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OperationResult(eu.bcvsolutions.idm.core.api.entity.OperationResult) RoleRequestEvent(eu.bcvsolutions.idm.core.model.event.RoleRequestEvent) BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) IdmBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission) IdmConceptRoleRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmConceptRoleRequestDto) UUID(java.util.UUID) IdmIdentityContractDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto) IdmRoleRequestDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleRequestDto) ForbiddenEntityException(eu.bcvsolutions.idm.core.api.exception.ForbiddenEntityException)

Example 5 with BasePermission

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;
}
Also used : BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) ArrayList(java.util.ArrayList) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID)

Aggregations

BasePermission (eu.bcvsolutions.idm.core.security.api.domain.BasePermission)18 IdmBasePermission (eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission)10 ArrayList (java.util.ArrayList)10 UUID (java.util.UUID)10 List (java.util.List)9 Autowired (org.springframework.beans.factory.annotation.Autowired)8 Lists (com.google.common.collect.Lists)7 HashSet (java.util.HashSet)7 Transactional (org.springframework.transaction.annotation.Transactional)7 DtoUtils (eu.bcvsolutions.idm.core.api.utils.DtoUtils)6 Serializable (java.io.Serializable)6 Collectors (java.util.stream.Collectors)6 IdmIdentityRoleDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto)5 IdmIdentityRoleFilter (eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter)5 IdmIdentityRoleService (eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService)5 AuthorizableType (eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType)5 HashMap (java.util.HashMap)5 Set (java.util.Set)5 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)5 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)5