Search in sources :

Example 11 with CurrentUser

use of org.hisp.dhis.user.CurrentUser in project dhis2-core by dhis2.

the class UserController method updateUserGroups.

protected void updateUserGroups(String pvUid, User parsed, User currentUser) {
    User user = userService.getUser(pvUid);
    // TODO: what is this doing? I don't understand how this is possible.
    if (currentUser != null && currentUser.getId() == user.getId()) {
        currentUser = currentUserService.getCurrentUser();
    }
    List<String> uids = getUids(parsed.getGroups());
    userGroupService.updateUserGroups(user, uids, currentUser);
}
Also used : CurrentUser(org.hisp.dhis.user.CurrentUser) User(org.hisp.dhis.user.User)

Example 12 with CurrentUser

use of org.hisp.dhis.user.CurrentUser in project dhis2-core by dhis2.

the class UserRoleController method addUserToRole.

@RequestMapping(value = "/{id}/users/{userId}", method = { RequestMethod.POST, RequestMethod.PUT })
@ResponseStatus(HttpStatus.NO_CONTENT)
public void addUserToRole(@PathVariable(value = "id") String pvId, @PathVariable("userId") String pvUserId, @CurrentUser User currentUser, HttpServletResponse response) throws WebMessageException {
    UserAuthorityGroup userAuthorityGroup = userService.getUserAuthorityGroup(pvId);
    if (userAuthorityGroup == null) {
        throw new WebMessageException(notFound("UserRole does not exist: " + pvId));
    }
    User user = userService.getUser(pvUserId);
    if (user == null) {
        throw new WebMessageException(notFound("User does not exist: " + pvId));
    }
    if (!aclService.canUpdate(currentUser, userAuthorityGroup)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    if (!user.getUserAuthorityGroups().contains(userAuthorityGroup)) {
        user.getUserAuthorityGroups().add(userAuthorityGroup);
        userService.updateUser(user);
    }
}
Also used : CurrentUser(org.hisp.dhis.user.CurrentUser) User(org.hisp.dhis.user.User) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 13 with CurrentUser

use of org.hisp.dhis.user.CurrentUser in project dhis2-core by dhis2.

the class AbstractFullReadOnlyController method getObjectListCsv.

@GetMapping(produces = "application/csv")
public void getObjectListCsv(@RequestParam Map<String, String> rpParameters, OrderParams orderParams, @CurrentUser User currentUser, @RequestParam(defaultValue = ",") char separator, @RequestParam(defaultValue = "false") boolean skipHeader, HttpServletResponse response) throws IOException {
    List<Order> orders = orderParams.getOrders(getSchema());
    List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
    List<String> filters = Lists.newArrayList(contextService.getParameterValues("filter"));
    WebOptions options = new WebOptions(rpParameters);
    WebMetadata metadata = new WebMetadata();
    if (fields.isEmpty()) {
        fields.addAll(Preset.defaultPreset().getFields());
    }
    // only support metadata
    if (!getSchema().isMetadata()) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
    }
    if (!aclService.canRead(currentUser, getEntityClass())) {
        throw new ReadAccessDeniedException("You don't have the proper permissions to read objects of this type.");
    }
    List<T> entities = getEntityList(metadata, options, filters, orders);
    CsvSchema schema;
    CsvSchema.Builder schemaBuilder = CsvSchema.builder();
    List<Property> properties = new ArrayList<>();
    for (String field : fields) {
        // then the group[id] part is simply ignored.
        for (String splitField : field.split(",")) {
            Property property = getSchema().getProperty(splitField);
            if (property == null || !property.isSimple()) {
                continue;
            }
            schemaBuilder.addColumn(property.getName());
            properties.add(property);
        }
    }
    schema = schemaBuilder.build().withColumnSeparator(separator);
    if (!skipHeader) {
        schema = schema.withHeader();
    }
    CsvMapper csvMapper = new CsvMapper();
    csvMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
    List<Map<String, Object>> csvObjects = entities.stream().map(e -> {
        Map<String, Object> map = new HashMap<>();
        for (Property property : properties) {
            Object value = ReflectionUtils.invokeMethod(e, property.getGetterMethod());
            map.put(property.getName(), value);
        }
        return map;
    }).collect(toList());
    csvMapper.writer(schema).writeValue(response.getWriter(), csvObjects);
    response.flushBuffer();
}
Also used : Order(org.hisp.dhis.query.Order) PathVariable(org.springframework.web.bind.annotation.PathVariable) Order(org.hisp.dhis.query.Order) RequestParam(org.springframework.web.bind.annotation.RequestParam) ReflectionUtils(org.hisp.dhis.system.util.ReflectionUtils) UserContext(org.hisp.dhis.common.UserContext) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) InclusionStrategy(org.hisp.dhis.node.config.InclusionStrategy) Pagination(org.hisp.dhis.query.Pagination) UserSettingKey(org.hisp.dhis.user.UserSettingKey) Autowired(org.springframework.beans.factory.annotation.Autowired) CurrentUser(org.hisp.dhis.user.CurrentUser) PaginationUtils(org.hisp.dhis.webapi.utils.PaginationUtils) NodeUtils(org.hisp.dhis.node.NodeUtils) UserSettingService(org.hisp.dhis.user.UserSettingService) Locale(java.util.Locale) Optional(com.google.common.base.Optional) Map(java.util.Map) Preset(org.hisp.dhis.node.Preset) Query(org.hisp.dhis.query.Query) ContextService(org.hisp.dhis.webapi.service.ContextService) LinkService(org.hisp.dhis.webapi.service.LinkService) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) CacheControl.noCache(org.springframework.http.CacheControl.noCache) QueryService(org.hisp.dhis.query.QueryService) Property(org.hisp.dhis.schema.Property) Defaults(org.hisp.dhis.fieldfilter.Defaults) SimpleNode(org.hisp.dhis.node.types.SimpleNode) List(java.util.List) Include(org.hisp.dhis.node.config.InclusionStrategy.Include) ComplexNode(org.hisp.dhis.node.types.ComplexNode) AttributeService(org.hisp.dhis.attribute.AttributeService) FieldFilterParams(org.hisp.dhis.fieldfilter.FieldFilterParams) AclService(org.hisp.dhis.security.acl.AclService) Schema(org.hisp.dhis.schema.Schema) RootNode(org.hisp.dhis.node.types.RootNode) Joiner(com.google.common.base.Joiner) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) WebMessageUtils.notFound(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound) CollectionNode(org.hisp.dhis.node.types.CollectionNode) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) HashMap(java.util.HashMap) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) ArrayList(java.util.ArrayList) Enums(com.google.common.base.Enums) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) QueryParserException(org.hisp.dhis.query.QueryParserException) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) Node(org.hisp.dhis.node.Node) Pager(org.hisp.dhis.common.Pager) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) HttpStatus(org.springframework.http.HttpStatus) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Collectors.toList(java.util.stream.Collectors.toList) OrderParams(org.hisp.dhis.dxf2.common.OrderParams) CurrentUserService(org.hisp.dhis.user.CurrentUserService) TranslateParams(org.hisp.dhis.dxf2.common.TranslateParams) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) ArrayList(java.util.ArrayList) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) Property(org.hisp.dhis.schema.Property) Map(java.util.Map) HashMap(java.util.HashMap) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 14 with CurrentUser

use of org.hisp.dhis.user.CurrentUser in project dhis2-core by dhis2.

the class AbstractFullReadOnlyController method getCollectionItem.

@GetMapping("/{uid}/{property}/{itemId}")
@ResponseBody
public RootNode getCollectionItem(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @PathVariable("itemId") String pvItemId, @RequestParam Map<String, String> parameters, TranslateParams translateParams, HttpServletResponse response, @CurrentUser User currentUser) throws Exception {
    setUserContext(currentUser, translateParams);
    try {
        if (!aclService.canRead(currentUser, getEntityClass())) {
            throw new ReadAccessDeniedException("You don't have the proper permissions to read objects of this type.");
        }
        RootNode rootNode = getObjectInternal(pvUid, parameters, Lists.newArrayList(), Lists.newArrayList(pvProperty + "[:all]"), currentUser);
        // TODO optimize this using field filter (collection filtering)
        if (!rootNode.getChildren().isEmpty() && rootNode.getChildren().get(0).isCollection()) {
            rootNode.getChildren().get(0).getChildren().stream().filter(Node::isComplex).forEach(node -> {
                node.getChildren().stream().filter(child -> child.isSimple() && child.getName().equals("id") && !((SimpleNode) child).getValue().equals(pvItemId)).forEach(child -> rootNode.getChildren().get(0).removeChild(node));
            });
        }
        if (rootNode.getChildren().isEmpty() || rootNode.getChildren().get(0).getChildren().isEmpty()) {
            throw new WebMessageException(notFound(pvProperty + " with ID " + pvItemId + " could not be found."));
        }
        cachePrivate(response);
        return rootNode;
    } finally {
        UserContext.reset();
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Order(org.hisp.dhis.query.Order) RequestParam(org.springframework.web.bind.annotation.RequestParam) ReflectionUtils(org.hisp.dhis.system.util.ReflectionUtils) UserContext(org.hisp.dhis.common.UserContext) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) InclusionStrategy(org.hisp.dhis.node.config.InclusionStrategy) Pagination(org.hisp.dhis.query.Pagination) UserSettingKey(org.hisp.dhis.user.UserSettingKey) Autowired(org.springframework.beans.factory.annotation.Autowired) CurrentUser(org.hisp.dhis.user.CurrentUser) PaginationUtils(org.hisp.dhis.webapi.utils.PaginationUtils) NodeUtils(org.hisp.dhis.node.NodeUtils) UserSettingService(org.hisp.dhis.user.UserSettingService) Locale(java.util.Locale) Optional(com.google.common.base.Optional) Map(java.util.Map) Preset(org.hisp.dhis.node.Preset) Query(org.hisp.dhis.query.Query) ContextService(org.hisp.dhis.webapi.service.ContextService) LinkService(org.hisp.dhis.webapi.service.LinkService) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) CacheControl.noCache(org.springframework.http.CacheControl.noCache) QueryService(org.hisp.dhis.query.QueryService) Property(org.hisp.dhis.schema.Property) Defaults(org.hisp.dhis.fieldfilter.Defaults) SimpleNode(org.hisp.dhis.node.types.SimpleNode) List(java.util.List) Include(org.hisp.dhis.node.config.InclusionStrategy.Include) ComplexNode(org.hisp.dhis.node.types.ComplexNode) AttributeService(org.hisp.dhis.attribute.AttributeService) FieldFilterParams(org.hisp.dhis.fieldfilter.FieldFilterParams) AclService(org.hisp.dhis.security.acl.AclService) Schema(org.hisp.dhis.schema.Schema) RootNode(org.hisp.dhis.node.types.RootNode) Joiner(com.google.common.base.Joiner) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) WebMessageUtils.notFound(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound) CollectionNode(org.hisp.dhis.node.types.CollectionNode) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) HashMap(java.util.HashMap) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) ArrayList(java.util.ArrayList) Enums(com.google.common.base.Enums) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) QueryParserException(org.hisp.dhis.query.QueryParserException) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) Node(org.hisp.dhis.node.Node) Pager(org.hisp.dhis.common.Pager) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) HttpStatus(org.springframework.http.HttpStatus) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Collectors.toList(java.util.stream.Collectors.toList) OrderParams(org.hisp.dhis.dxf2.common.OrderParams) CurrentUserService(org.hisp.dhis.user.CurrentUserService) TranslateParams(org.hisp.dhis.dxf2.common.TranslateParams) RootNode(org.hisp.dhis.node.types.RootNode) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 15 with CurrentUser

use of org.hisp.dhis.user.CurrentUser in project dhis2-core by dhis2.

the class MessageConversationController method setUserAssigned.

// --------------------------------------------------------------------------
// Assign user
// --------------------------------------------------------------------------
@PostMapping(value = "/{uid}/assign", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseBody
public RootNode setUserAssigned(@PathVariable String uid, @RequestParam(required = false) String userId, @CurrentUser User currentUser, HttpServletResponse response) {
    RootNode responseNode = new RootNode("response");
    if (!canModifyUserConversation(currentUser, currentUser) && (messageService.hasAccessToManageFeedbackMessages(currentUser))) {
        throw new UpdateAccessDeniedException("Not authorized to modify this object.");
    }
    org.hisp.dhis.message.MessageConversation messageConversation = messageService.getMessageConversation(uid);
    if (messageConversation == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        responseNode.addChild(new SimpleNode("message", "No MessageConversation found for the given ID."));
        return responseNode;
    }
    User userToAssign;
    if ((userToAssign = userService.getUser(userId)) == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        responseNode.addChild(new SimpleNode("message", "Could not find user to assign"));
        return responseNode;
    }
    if (messageConversation.getMessageType() == MessageType.TICKET && !configurationService.isUserInFeedbackRecipientUserGroup(userToAssign)) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        responseNode.addChild(new SimpleNode("message", "User provided is not a member of the system's feedback recipient group"));
        return responseNode;
    }
    messageConversation.setAssignee(userToAssign);
    messageService.updateMessageConversation(messageConversation);
    responseNode.addChild(new SimpleNode("message", "User " + userToAssign.getName() + " was assigned successfully"));
    response.setStatus(HttpServletResponse.SC_OK);
    return responseNode;
}
Also used : RootNode(org.hisp.dhis.node.types.RootNode) CurrentUser(org.hisp.dhis.user.CurrentUser) User(org.hisp.dhis.user.User) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) SimpleNode(org.hisp.dhis.node.types.SimpleNode) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

CurrentUser (org.hisp.dhis.user.CurrentUser)21 User (org.hisp.dhis.user.User)21 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)9 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)8 CollectionNode (org.hisp.dhis.node.types.CollectionNode)8 RootNode (org.hisp.dhis.node.types.RootNode)8 SimpleNode (org.hisp.dhis.node.types.SimpleNode)8 UpdateAccessDeniedException (org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException)7 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IdentifiableObject (org.hisp.dhis.common.IdentifiableObject)3 PostMapping (org.springframework.web.bind.annotation.PostMapping)3 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 CsvMapper (com.fasterxml.jackson.dataformat.csv.CsvMapper)2 CsvSchema (com.fasterxml.jackson.dataformat.csv.CsvSchema)2 Enums (com.google.common.base.Enums)2 Joiner (com.google.common.base.Joiner)2 Optional (com.google.common.base.Optional)2 Lists (com.google.common.collect.Lists)2 IOException (java.io.IOException)2