Search in sources :

Example 76 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project dhis2-core by dhis2.

the class DefaultTrackerOwnershipManager method transferOwnership.

// -------------------------------------------------------------------------
// Implementation
// -------------------------------------------------------------------------
@Override
@Transactional
public void transferOwnership(TrackedEntityInstance entityInstance, Program program, OrganisationUnit orgUnit, boolean skipAccessValidation, boolean createIfNotExists) {
    if (entityInstance == null || program == null || orgUnit == null) {
        return;
    }
    if (hasAccess(currentUserService.getCurrentUser(), entityInstance, program) || skipAccessValidation) {
        TrackedEntityProgramOwner teProgramOwner = trackedEntityProgramOwnerService.getTrackedEntityProgramOwner(entityInstance.getId(), program.getId());
        if (teProgramOwner != null) {
            if (!teProgramOwner.getOrganisationUnit().equals(orgUnit)) {
                ProgramOwnershipHistory programOwnershipHistory = new ProgramOwnershipHistory(program, entityInstance, teProgramOwner.getOrganisationUnit(), teProgramOwner.getLastUpdated(), teProgramOwner.getCreatedBy());
                programOwnershipHistoryService.addProgramOwnershipHistory(programOwnershipHistory);
                trackedEntityProgramOwnerService.updateTrackedEntityProgramOwner(entityInstance, program, orgUnit);
            }
        } else if (createIfNotExists) {
            trackedEntityProgramOwnerService.createTrackedEntityProgramOwner(entityInstance, program, orgUnit);
        }
        ownerCache.invalidate(getOwnershipCacheKey(() -> entityInstance.getId(), program));
    } else {
        log.error("Unauthorized attempt to change ownership");
        throw new AccessDeniedException("User does not have access to change ownership for the entity-program combination");
    }
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) ProgramOwnershipHistory(org.hisp.dhis.program.ProgramOwnershipHistory) Transactional(org.springframework.transaction.annotation.Transactional)

Example 77 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project dhis2-core by dhis2.

the class MessageConversationController method postMessageConversationReply.

// --------------------------------------------------------------------------
// POST for reply on existing MessageConversation
// --------------------------------------------------------------------------
@PostMapping("/{uid}")
@ResponseBody
public WebMessage postMessageConversationReply(@PathVariable("uid") String uid, @RequestBody String message, @RequestParam(value = "internal", defaultValue = "false") boolean internal, @RequestParam(value = "attachments", required = false) Set<String> attachments, @CurrentUser User currentUser, HttpServletRequest request) {
    String metaData = MessageService.META_USER_AGENT + request.getHeader(ContextUtils.HEADER_USER_AGENT);
    org.hisp.dhis.message.MessageConversation conversation = messageService.getMessageConversation(uid);
    if (conversation == null) {
        return notFound("Message conversation does not exist: " + uid);
    }
    if (internal && !messageService.hasAccessToManageFeedbackMessages(currentUser)) {
        throw new AccessDeniedException("Not authorized to send internal messages");
    }
    Set<FileResource> fileResources = new HashSet<>();
    if (attachments == null) {
        attachments = new HashSet<>();
    }
    for (String fileResourceUid : attachments) {
        FileResource fileResource = fileResourceService.getFileResource(fileResourceUid);
        if (fileResource == null) {
            return conflict("Attachment '" + fileResourceUid + "' not found.");
        }
        if (!fileResource.getDomain().equals(FileResourceDomain.MESSAGE_ATTACHMENT) || fileResource.isAssigned()) {
            return conflict("Attachment '" + fileResourceUid + "' is already used or not a valid attachment.");
        }
        fileResource.setAssigned(true);
        fileResourceService.updateFileResource(fileResource);
        fileResources.add(fileResource);
    }
    messageService.sendReply(conversation, message, metaData, internal, fileResources);
    return created("Message conversation created").setLocation(MessageConversationSchemaDescriptor.API_ENDPOINT + "/" + conversation.getUid());
}
Also used : UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) FileResource(org.hisp.dhis.fileresource.FileResource) HashSet(java.util.HashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 78 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project dhis2-core by dhis2.

the class MessageConversationController method getMessage.

/**
 * /* Returns the specified message after making sure the user has access to
 * it.
 *
 * @param mcUid the message conversation UID.
 * @param msgUid the message UID.
 * @param user the user.
 * @return a {@link Message}.
 * @throws WebMessageException
 */
private Message getMessage(String mcUid, String msgUid, User user) throws WebMessageException {
    org.hisp.dhis.message.MessageConversation conversation = messageService.getMessageConversation(mcUid);
    if (conversation == null) {
        throw new WebMessageException(notFound(String.format("No message conversation with uid '%s'", mcUid)));
    }
    if (!canReadMessageConversation(user, conversation)) {
        throw new AccessDeniedException("Not authorized to access this conversation.");
    }
    List<Message> messages = conversation.getMessages().stream().filter(msg -> msg.getUid().equals(msgUid)).collect(Collectors.toList());
    if (messages.size() < 1) {
        throw new WebMessageException(notFound(String.format("No message with uid '%s' in messageConversation '%s", msgUid, mcUid)));
    }
    Message message = messages.get(0);
    if (message.isInternal() && !configurationService.isUserInFeedbackRecipientUserGroup(user)) {
        throw new WebMessageException(conflict("Not authorized to access this message"));
    }
    return message;
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Arrays(java.util.Arrays) Order(org.hisp.dhis.query.Order) RequestParam(org.springframework.web.bind.annotation.RequestParam) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) UserMessage(org.hisp.dhis.message.UserMessage) WebMessageUtils.created(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.created) Pagination(org.hisp.dhis.query.Pagination) Autowired(org.springframework.beans.factory.annotation.Autowired) OrganisationUnitService(org.hisp.dhis.organisationunit.OrganisationUnitService) MessageService(org.hisp.dhis.message.MessageService) CurrentUser(org.hisp.dhis.user.CurrentUser) MessageConversationStatus(org.hisp.dhis.message.MessageConversationStatus) MessageConversation(org.hisp.dhis.webapi.webdomain.MessageConversation) FileResourceService(org.hisp.dhis.fileresource.FileResourceService) Map(java.util.Map) Message(org.hisp.dhis.message.Message) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) PostMapping(org.springframework.web.bind.annotation.PostMapping) Query(org.hisp.dhis.query.Query) UserService(org.hisp.dhis.user.UserService) MessageConversationPriority(org.hisp.dhis.message.MessageConversationPriority) MessageType(org.hisp.dhis.message.MessageType) UserGroup(org.hisp.dhis.user.UserGroup) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) Set(java.util.Set) Junction(org.hisp.dhis.query.Junction) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Defaults(org.hisp.dhis.fieldfilter.Defaults) SimpleNode(org.hisp.dhis.node.types.SimpleNode) List(java.util.List) FileResourceUtils(org.hisp.dhis.webapi.utils.FileResourceUtils) UserGroupService(org.hisp.dhis.user.UserGroupService) WebMessageUtils.conflict(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RootNode(org.hisp.dhis.node.types.RootNode) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) WebMessageUtils.notFound(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound) CollectionNode(org.hisp.dhis.node.types.CollectionNode) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Controller(org.springframework.stereotype.Controller) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) QueryParserException(org.hisp.dhis.query.QueryParserException) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) Pager(org.hisp.dhis.common.Pager) FileResource(org.hisp.dhis.fileresource.FileResource) HttpServletResponse(javax.servlet.http.HttpServletResponse) MessageConversationSchemaDescriptor(org.hisp.dhis.schema.descriptors.MessageConversationSchemaDescriptor) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) HttpStatus(org.springframework.http.HttpStatus) ConfigurationService(org.hisp.dhis.configuration.ConfigurationService) FileResourceDomain(org.hisp.dhis.fileresource.FileResourceDomain) Collections(java.util.Collections) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) UserMessage(org.hisp.dhis.message.UserMessage) Message(org.hisp.dhis.message.Message) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException)

Example 79 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project dhis2-core by dhis2.

the class InterpretationController method deleteComment.

@DeleteMapping("/{uid}/comments/{cuid}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ResponseBody
public WebMessage deleteComment(@PathVariable("uid") String uid, @PathVariable("cuid") String cuid, HttpServletResponse response) {
    Interpretation interpretation = interpretationService.getInterpretation(uid);
    if (interpretation == null) {
        return conflict("Interpretation does not exist: " + uid);
    }
    Iterator<InterpretationComment> iterator = interpretation.getComments().iterator();
    while (iterator.hasNext()) {
        InterpretationComment comment = iterator.next();
        if (comment.getUid().equals(cuid)) {
            if (!currentUserService.getCurrentUser().equals(comment.getCreatedBy()) && !currentUserService.currentUserIsSuper()) {
                throw new AccessDeniedException("You are not allowed to delete this comment.");
            }
            iterator.remove();
        }
    }
    interpretationService.updateInterpretation(interpretation);
    return null;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) InterpretationComment(org.hisp.dhis.interpretation.InterpretationComment) Interpretation(org.hisp.dhis.interpretation.Interpretation) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 80 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project dhis2-core by dhis2.

the class InterpretationController method updateInterpretation.

// -------------------------------------------------------------------------
// Interpretation update
// -------------------------------------------------------------------------
@PutMapping("/{uid}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ResponseBody
public WebMessage updateInterpretation(@PathVariable("uid") String uid, @RequestBody String text) {
    Interpretation interpretation = interpretationService.getInterpretation(uid);
    if (interpretation == null) {
        return notFound("Interpretation does not exist: " + uid);
    }
    if (!currentUserService.getCurrentUser().equals(interpretation.getCreatedBy()) && !currentUserService.currentUserIsSuper()) {
        throw new AccessDeniedException("You are not allowed to update this interpretation.");
    }
    interpretationService.updateInterpretationText(interpretation, text);
    return null;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) Interpretation(org.hisp.dhis.interpretation.Interpretation) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PutMapping(org.springframework.web.bind.annotation.PutMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

AccessDeniedException (org.springframework.security.access.AccessDeniedException)189 Test (org.junit.Test)32 Test (org.junit.jupiter.api.Test)21 Authentication (org.springframework.security.core.Authentication)18 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)17 ArrayList (java.util.ArrayList)15 ApplicationUser (org.finra.herd.model.dto.ApplicationUser)14 SecurityUserWrapper (org.finra.herd.model.dto.SecurityUserWrapper)14 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)14 AbstractServiceTest (org.finra.herd.service.AbstractServiceTest)13 Method (java.lang.reflect.Method)12 JoinPoint (org.aspectj.lang.JoinPoint)11 MethodSignature (org.aspectj.lang.reflect.MethodSignature)11 SecurityContext (org.springframework.security.core.context.SecurityContext)11 NamespaceAuthorization (org.finra.herd.model.api.xml.NamespaceAuthorization)10 Credential (com.sequenceiq.cloudbreak.domain.Credential)8 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)8 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)8 ModelAndView (org.springframework.web.servlet.ModelAndView)8 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)7