Search in sources :

Example 71 with WebMessageException

use of org.hisp.dhis.dxf2.webmessage.WebMessageException in project dhis2-core by dhis2.

the class DashboardController method postJsonItemContent.

@RequestMapping(value = "/{dashboardUid}/items/content", method = RequestMethod.POST)
public void postJsonItemContent(HttpServletResponse response, HttpServletRequest request, @PathVariable String dashboardUid, @RequestParam DashboardItemType type, @RequestParam("id") String contentUid) throws Exception {
    Dashboard dashboard = dashboardService.getDashboard(dashboardUid);
    if (dashboard == null) {
        throw new WebMessageException(WebMessageUtils.notFound("Dashboard does not exist: " + dashboardUid));
    }
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), dashboard)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this dashboard.");
    }
    DashboardItem item = dashboardService.addItemContent(dashboardUid, type, contentUid);
    if (item == null) {
        throw new WebMessageException(WebMessageUtils.conflict("Max number of dashboard items reached: " + MAX_ITEMS));
    } else {
        response.addHeader("Location", DashboardItemSchemaDescriptor.API_ENDPOINT + "/" + item.getUid());
        webMessageService.send(WebMessageUtils.created("Dashboard item created"), response, request);
    }
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) Dashboard(org.hisp.dhis.dashboard.Dashboard) DashboardItem(org.hisp.dhis.dashboard.DashboardItem) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 72 with WebMessageException

use of org.hisp.dhis.dxf2.webmessage.WebMessageException in project dhis2-core by dhis2.

the class AbstractCrudController method getObjectInternal.

@SuppressWarnings("unchecked")
private RootNode getObjectInternal(String uid, Map<String, String> parameters, List<String> filters, List<String> fields, User user) throws Exception {
    WebOptions options = new WebOptions(parameters);
    List<T> entities = getEntity(uid, options);
    if (entities.isEmpty()) {
        throw new WebMessageException(WebMessageUtils.notFound(getEntityClass(), uid));
    }
    Query query = queryService.getQueryFromUrl(getEntityClass(), filters, new ArrayList<>(), options.getRootJunction());
    query.setUser(user);
    query.setObjects(entities);
    entities = (List<T>) queryService.query(query);
    handleLinksAndAccess(entities, fields, true, user);
    for (T entity : entities) {
        postProcessEntity(entity);
        postProcessEntity(entity, options, parameters);
    }
    CollectionNode collectionNode = fieldFilterService.filter(getEntityClass(), entities, fields);
    if (options.isTrue("useWrapper") || entities.size() > 1) {
        RootNode rootNode = NodeUtils.createMetadata(collectionNode);
        rootNode.getConfig().setInclusionStrategy(getInclusionStrategy(parameters.get("inclusionStrategy")));
        return rootNode;
    } else {
        List<Node> children = collectionNode.getChildren();
        RootNode rootNode;
        if (!children.isEmpty()) {
            rootNode = NodeUtils.createRootNode(children.get(0));
        } else {
            rootNode = NodeUtils.createRootNode(new ComplexNode(getSchema().getSingular()));
        }
        rootNode.getConfig().setInclusionStrategy(getInclusionStrategy(parameters.get("inclusionStrategy")));
        return rootNode;
    }
}
Also used : RootNode(org.hisp.dhis.node.types.RootNode) Query(org.hisp.dhis.query.Query) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) ComplexNode(org.hisp.dhis.node.types.ComplexNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) SimpleNode(org.hisp.dhis.node.types.SimpleNode) ComplexNode(org.hisp.dhis.node.types.ComplexNode) RootNode(org.hisp.dhis.node.types.RootNode) CollectionNode(org.hisp.dhis.node.types.CollectionNode) Node(org.hisp.dhis.node.Node) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) CollectionNode(org.hisp.dhis.node.types.CollectionNode)

Example 73 with WebMessageException

use of org.hisp.dhis.dxf2.webmessage.WebMessageException in project dhis2-core by dhis2.

the class AccountController method createAccount.

@RequestMapping(method = RequestMethod.POST)
public void createAccount(@RequestParam String username, @RequestParam String firstName, @RequestParam String surname, @RequestParam String password, @RequestParam String email, @RequestParam String phoneNumber, @RequestParam String employer, @RequestParam(required = false) String inviteUsername, @RequestParam(required = false) String inviteToken, @RequestParam(required = false) String inviteCode, @RequestParam(value = "recaptcha_challenge_field", required = false) String recapChallenge, @RequestParam(value = "recaptcha_response_field", required = false) String recapResponse, HttpServletRequest request, HttpServletResponse response) throws WebMessageException {
    UserCredentials credentials = null;
    boolean invitedByEmail = (inviteUsername != null && !inviteUsername.isEmpty());
    boolean canChooseUsername = true;
    if (invitedByEmail) {
        credentials = userService.getUserCredentialsByUsername(inviteUsername);
        if (credentials == null) {
            throw new WebMessageException(WebMessageUtils.badRequest("Invitation link not valid"));
        }
        boolean canRestore = securityService.canRestore(credentials, inviteToken, inviteCode, RestoreType.INVITE);
        if (!canRestore) {
            throw new WebMessageException(WebMessageUtils.badRequest("Invitation code not valid"));
        }
        RestoreOptions restoreOptions = securityService.getRestoreOptions(inviteToken);
        canChooseUsername = restoreOptions.isUsernameChoice();
    } else {
        boolean allowed = configurationService.getConfiguration().selfRegistrationAllowed();
        if (!allowed) {
            throw new WebMessageException(WebMessageUtils.badRequest("User self registration is not allowed"));
        }
    }
    // ---------------------------------------------------------------------
    // Trim input
    // ---------------------------------------------------------------------
    username = StringUtils.trimToNull(username);
    firstName = StringUtils.trimToNull(firstName);
    surname = StringUtils.trimToNull(surname);
    password = StringUtils.trimToNull(password);
    email = StringUtils.trimToNull(email);
    phoneNumber = StringUtils.trimToNull(phoneNumber);
    employer = StringUtils.trimToNull(employer);
    recapChallenge = StringUtils.trimToNull(recapChallenge);
    recapResponse = StringUtils.trimToNull(recapResponse);
    CredentialsInfo credentialsInfo = new CredentialsInfo(username, password, email, true);
    if (username == null || username.trim().length() > MAX_LENGTH) {
        throw new WebMessageException(WebMessageUtils.badRequest("User name is not specified or invalid"));
    }
    UserCredentials usernameAlreadyTakenCredentials = userService.getUserCredentialsByUsername(username);
    if (canChooseUsername && usernameAlreadyTakenCredentials != null) {
        throw new WebMessageException(WebMessageUtils.badRequest("User name is already taken"));
    }
    if (firstName == null || firstName.trim().length() > MAX_LENGTH) {
        throw new WebMessageException(WebMessageUtils.badRequest("First name is not specified or invalid"));
    }
    if (surname == null || surname.trim().length() > MAX_LENGTH) {
        throw new WebMessageException(WebMessageUtils.badRequest("Last name is not specified or invalid"));
    }
    if (password == null) {
        throw new WebMessageException(WebMessageUtils.badRequest("Password is not specified"));
    }
    PasswordValidationResult result = passwordValidationService.validate(credentialsInfo);
    if (!result.isValid()) {
        throw new WebMessageException(WebMessageUtils.badRequest(result.getErrorMessage()));
    }
    if (email == null || !ValidationUtils.emailIsValid(email)) {
        throw new WebMessageException(WebMessageUtils.badRequest("Email is not specified or invalid"));
    }
    if (phoneNumber == null || phoneNumber.trim().length() > MAX_PHONE_NO_LENGTH) {
        throw new WebMessageException(WebMessageUtils.badRequest("Phone number is not specified or invalid"));
    }
    if (employer == null || employer.trim().length() > MAX_LENGTH) {
        throw new WebMessageException(WebMessageUtils.badRequest("Employer is not specified or invalid"));
    }
    if (!systemSettingManager.selfRegistrationNoRecaptcha()) {
        if (recapChallenge == null) {
            throw new WebMessageException(WebMessageUtils.badRequest("Recaptcha challenge must be specified"));
        }
        if (recapResponse == null) {
            throw new WebMessageException(WebMessageUtils.badRequest("Recaptcha response must be specified"));
        }
        // ---------------------------------------------------------------------
        // Check result from API, return 500 if not
        // ---------------------------------------------------------------------
        String[] results = checkRecaptcha(KEY, request.getRemoteAddr(), recapChallenge, recapResponse);
        if (results == null || results.length == 0) {
            throw new WebMessageException(WebMessageUtils.error("Captcha could not be verified due to a server error"));
        }
        if (!TRUE.equalsIgnoreCase(results[0])) {
            log.info("Recaptcha failed with code: " + (results.length > 0 ? results[1] : ""));
            throw new WebMessageException(WebMessageUtils.badRequest("The characters you entered did not match the word verification, try again"));
        }
    }
    if (invitedByEmail) {
        boolean restored = securityService.restore(credentials, inviteToken, inviteCode, password, RestoreType.INVITE);
        if (!restored) {
            log.info("Invite restore failed for: " + inviteUsername);
            throw new WebMessageException(WebMessageUtils.badRequest("Unable to create invited user account"));
        }
        User user = credentials.getUserInfo();
        user.setFirstName(firstName);
        user.setSurname(surname);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        user.setEmployer(employer);
        if (canChooseUsername) {
            credentials.setUsername(username);
        } else {
            username = credentials.getUsername();
        }
        userService.encodeAndSetPassword(credentials, password);
        userService.updateUser(user);
        userService.updateUserCredentials(credentials);
        log.info("User " + username + " accepted invitation for " + inviteUsername);
    } else {
        UserAuthorityGroup userRole = configurationService.getConfiguration().getSelfRegistrationRole();
        OrganisationUnit orgUnit = configurationService.getConfiguration().getSelfRegistrationOrgUnit();
        User user = new User();
        user.setFirstName(firstName);
        user.setSurname(surname);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        user.setEmployer(employer);
        user.getOrganisationUnits().add(orgUnit);
        user.getDataViewOrganisationUnits().add(orgUnit);
        credentials = new UserCredentials();
        credentials.setUsername(username);
        userService.encodeAndSetPassword(credentials, password);
        credentials.setSelfRegistered(true);
        credentials.setUserInfo(user);
        credentials.getUserAuthorityGroups().add(userRole);
        user.setUserCredentials(credentials);
        userService.addUser(user);
        userService.addUserCredentials(credentials);
        log.info("Created user with username: " + username);
    }
    Set<GrantedAuthority> authorities = getAuthorities(credentials.getUserAuthorityGroups());
    authenticate(username, password, authorities, request);
    webMessageService.send(WebMessageUtils.ok("Account created"), response, request);
}
Also used : RestoreOptions(org.hisp.dhis.security.RestoreOptions) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 74 with WebMessageException

use of org.hisp.dhis.dxf2.webmessage.WebMessageException in project dhis2-core by dhis2.

the class AbstractCrudController method getCollectionItem.

//--------------------------------------------------------------------------
// Identifiable object collections add, delete
//--------------------------------------------------------------------------
@RequestMapping(value = "/{uid}/{property}/{itemId}", method = RequestMethod.GET)
@ResponseBody
public RootNode getCollectionItem(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @PathVariable("itemId") String pvItemId, @RequestParam Map<String, String> parameters, TranslateParams translateParams, HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = currentUserService.getCurrentUser();
    setUserContext(user, translateParams);
    if (!aclService.canRead(user, 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]"), user);
    // 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(WebMessageUtils.notFound(pvProperty + " with ID " + pvItemId + " could not be found."));
    }
    return rootNode;
}
Also used : ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) PathVariable(org.springframework.web.bind.annotation.PathVariable) Order(org.hisp.dhis.query.Order) RequestParam(org.springframework.web.bind.annotation.RequestParam) ErrorReport(org.hisp.dhis.feedback.ErrorReport) UserContext(org.hisp.dhis.common.UserContext) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) MergeService(org.hisp.dhis.schema.MergeService) RenderService(org.hisp.dhis.render.RenderService) InclusionStrategy(org.hisp.dhis.node.config.InclusionStrategy) UserSettingKey(org.hisp.dhis.user.UserSettingKey) Autowired(org.springframework.beans.factory.annotation.Autowired) WebMessageService(org.hisp.dhis.webapi.service.WebMessageService) NodeUtils(org.hisp.dhis.node.NodeUtils) UserSettingService(org.hisp.dhis.user.UserSettingService) Optional(com.google.common.base.Optional) MetadataImportService(org.hisp.dhis.dxf2.metadata.MetadataImportService) Locale(java.util.Locale) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Preset(org.hisp.dhis.node.Preset) PagerUtils(org.hisp.dhis.common.PagerUtils) Status(org.hisp.dhis.feedback.Status) Query(org.hisp.dhis.query.Query) ContextService(org.hisp.dhis.webapi.service.ContextService) DefaultRenderService(org.hisp.dhis.render.DefaultRenderService) LinkService(org.hisp.dhis.webapi.service.LinkService) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) MediaType(org.springframework.http.MediaType) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) SchemaService(org.hisp.dhis.schema.SchemaService) QueryService(org.hisp.dhis.query.QueryService) Property(org.hisp.dhis.schema.Property) Collectors(java.util.stream.Collectors) ImportReportMode(org.hisp.dhis.dxf2.metadata.feedback.ImportReportMode) MetadataExportService(org.hisp.dhis.dxf2.metadata.MetadataExportService) SimpleNode(org.hisp.dhis.node.types.SimpleNode) ObjectTranslation(org.hisp.dhis.translation.ObjectTranslation) List(java.util.List) ComplexNode(org.hisp.dhis.node.types.ComplexNode) Type(java.lang.reflect.Type) AclService(org.hisp.dhis.security.acl.AclService) Schema(org.hisp.dhis.schema.Schema) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RootNode(org.hisp.dhis.node.types.RootNode) Joiner(com.google.common.base.Joiner) HibernateCacheManager(org.hisp.dhis.cache.HibernateCacheManager) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) ImportReport(org.hisp.dhis.dxf2.metadata.feedback.ImportReport) CollectionNode(org.hisp.dhis.node.types.CollectionNode) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) CreateAccessDeniedException(org.hisp.dhis.hibernate.exception.CreateAccessDeniedException) HashMap(java.util.HashMap) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) Enums(com.google.common.base.Enums) TypeReport(org.hisp.dhis.feedback.TypeReport) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) Charset(java.nio.charset.Charset) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) User(org.hisp.dhis.user.User) ErrorCode(org.hisp.dhis.feedback.ErrorCode) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) WebMessageUtils(org.hisp.dhis.dxf2.webmessage.WebMessageUtils) ObjectReport(org.hisp.dhis.feedback.ObjectReport) QueryParserException(org.hisp.dhis.query.QueryParserException) IdentifiableObjects(org.hisp.dhis.common.IdentifiableObjects) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) StreamUtils(org.springframework.util.StreamUtils) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) Node(org.hisp.dhis.node.Node) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) Pager(org.hisp.dhis.common.Pager) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) MetadataImportParams(org.hisp.dhis.dxf2.metadata.MetadataImportParams) CollectionService(org.hisp.dhis.dxf2.metadata.collection.CollectionService) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) HttpStatus(org.springframework.http.HttpStatus) OrderParams(org.hisp.dhis.dxf2.common.OrderParams) ParameterizedType(java.lang.reflect.ParameterizedType) CurrentUserService(org.hisp.dhis.user.CurrentUserService) TranslateParams(org.hisp.dhis.dxf2.common.TranslateParams) StringUtils(org.springframework.util.StringUtils) RootNode(org.hisp.dhis.node.types.RootNode) User(org.hisp.dhis.user.User) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 75 with WebMessageException

use of org.hisp.dhis.dxf2.webmessage.WebMessageException in project dhis2-core by dhis2.

the class AbstractCrudController method updateObjectProperty.

@RequestMapping(value = "/{uid}/{property}", method = { RequestMethod.PUT, RequestMethod.PATCH })
public void updateObjectProperty(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @RequestParam Map<String, String> rpParameters, HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebOptions options = new WebOptions(rpParameters);
    List<T> entities = getEntity(pvUid, options);
    if (entities.isEmpty()) {
        throw new WebMessageException(WebMessageUtils.notFound(getEntityClass(), pvUid));
    }
    if (!getSchema().haveProperty(pvProperty)) {
        throw new WebMessageException(WebMessageUtils.notFound("Property " + pvProperty + " does not exist on " + getEntityName()));
    }
    Property property = getSchema().getProperty(pvProperty);
    T persistedObject = entities.get(0);
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), persistedObject)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    if (!property.isWritable()) {
        throw new UpdateAccessDeniedException("This property is read-only.");
    }
    T object = deserialize(request);
    if (object == null) {
        throw new WebMessageException(WebMessageUtils.badRequest("Unknown payload format."));
    }
    Object value = property.getGetterMethod().invoke(object);
    property.getSetterMethod().invoke(persistedObject, value);
    manager.update(persistedObject);
    postPatchEntity(persistedObject);
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) Property(org.hisp.dhis.schema.Property) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)134 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)118 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)31 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)28 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)27 DataSet (org.hisp.dhis.dataset.DataSet)21 Period (org.hisp.dhis.period.Period)21 User (org.hisp.dhis.user.User)20 UpdateAccessDeniedException (org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException)18 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)15 ArrayList (java.util.ArrayList)14 DataElementCategoryOptionCombo (org.hisp.dhis.dataelement.DataElementCategoryOptionCombo)14 Interpretation (org.hisp.dhis.interpretation.Interpretation)13 Date (java.util.Date)9 WebOptions (org.hisp.dhis.webapi.webdomain.WebOptions)9 InputStream (java.io.InputStream)8 Grid (org.hisp.dhis.common.Grid)8 Event (org.hisp.dhis.dxf2.events.event.Event)8 MetadataImportParams (org.hisp.dhis.dxf2.metadata.MetadataImportParams)8 WebMessage (org.hisp.dhis.dxf2.webmessage.WebMessage)8