Search in sources :

Example 1 with WebMessageUtils.error

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.error 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 2 with WebMessageUtils.error

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

the class EventController method getEventDataValueFile.

@RequestMapping(value = "/files", method = RequestMethod.GET)
@PreAuthorize("hasRole('ALL') or hasRole('F_TRACKED_ENTITY_DATAVALUE_ADD') or hasRole('F_TRACKED_ENTITY_DATAVALUE_READ')")
public void getEventDataValueFile(@RequestParam String eventUid, @RequestParam String dataElementUid, HttpServletResponse response, HttpServletRequest request) throws Exception {
    Event event = eventService.getEvent(eventUid);
    if (event == null) {
        throw new WebMessageException(WebMessageUtils.notFound("Event not found for ID " + eventUid));
    }
    DataElement dataElement = dataElementService.getDataElement(dataElementUid);
    if (dataElement == null) {
        throw new WebMessageException(WebMessageUtils.notFound("DataElement not found for ID " + dataElementUid));
    }
    if (!dataElement.isFileType()) {
        throw new WebMessageException(WebMessageUtils.conflict("DataElement must be of type file"));
    }
    // ---------------------------------------------------------------------
    // Get file resource
    // ---------------------------------------------------------------------
    String uid = null;
    for (DataValue value : event.getDataValues()) {
        if (value.getDataElement() != null && value.getDataElement().equals(dataElement.getUid())) {
            uid = value.getValue();
            break;
        }
    }
    if (uid == null) {
        throw new WebMessageException(WebMessageUtils.conflict("DataElement must be of type file"));
    }
    FileResource fileResource = fileResourceService.getFileResource(uid);
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(WebMessageUtils.notFound("A data value file resource with id " + uid + " does not exist."));
    }
    if (fileResource.getStorageStatus() != FileResourceStorageStatus.STORED) {
        // -----------------------------------------------------------------
        // The FileResource exists and is tied to DataValue, however the 
        // underlying file content still not stored to external file store
        // -----------------------------------------------------------------
        WebMessage webMessage = WebMessageUtils.conflict("The content is being processed and is not available yet. Try again later.", "The content requested is in transit to the file store and will be available at a later time.");
        webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
        throw new WebMessageException(webMessage);
    }
    ByteSource content = fileResourceService.getFileResourceContent(fileResource);
    if (content == null) {
        throw new WebMessageException(WebMessageUtils.notFound("The referenced file could not be found"));
    }
    // ---------------------------------------------------------------------
    // Attempt to build signed URL request for content and redirect
    // ---------------------------------------------------------------------
    URI signedGetUri = fileResourceService.getSignedGetFileResourceContentUri(uid);
    if (signedGetUri != null) {
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.setHeader(HttpHeaders.LOCATION, signedGetUri.toASCIIString());
        return;
    }
    // ---------------------------------------------------------------------
    // Build response and return
    // ---------------------------------------------------------------------
    response.setContentType(fileResource.getContentType());
    response.setContentLength(new Long(fileResource.getContentLength()).intValue());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    // ---------------------------------------------------------------------
    // Request signing is not available, stream content back to client
    // ---------------------------------------------------------------------
    InputStream inputStream = null;
    try {
        inputStream = content.openStream();
        IOUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException e) {
        throw new WebMessageException(WebMessageUtils.error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend. " + "Depending on the provider the root cause could be network or file system related."));
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.dxf2.events.event.DataValue) InputStream(java.io.InputStream) FileResource(org.hisp.dhis.fileresource.FileResource) IOException(java.io.IOException) URI(java.net.URI) DataElement(org.hisp.dhis.dataelement.DataElement) FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) Event(org.hisp.dhis.dxf2.events.event.Event) ByteSource(com.google.common.io.ByteSource) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with WebMessageUtils.error

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

the class StaticContentController method updateStaticContent.

/**
     * Uploads PNG images based on a key. Only accepts PNG and white listed keys.
     *
     * @param key  the key.
     * @param file the image file.
     */
@PreAuthorize("hasRole('ALL') or hasRole('F_SYSTEM_SETTING')")
@ResponseStatus(HttpStatus.NO_CONTENT)
@RequestMapping(value = "/{key}", method = RequestMethod.POST)
public void updateStaticContent(@PathVariable("key") String key, @RequestParam(value = "file") MultipartFile file) throws WebMessageException, IOException {
    if (file == null || file.isEmpty()) {
        throw new WebMessageException(WebMessageUtils.badRequest("Missing parameter 'file'"));
    }
    // Only PNG is accepted at the current time
    MimeType mimeType = MimeTypeUtils.parseMimeType(file.getContentType());
    if (!mimeType.isCompatibleWith(MimeTypeUtils.IMAGE_PNG)) {
        throw new WebMessageException(new WebMessage(Status.WARNING, HttpStatus.UNSUPPORTED_MEDIA_TYPE));
    }
    if (!KEY_WHITELIST_MAP.containsKey(key)) {
        throw new WebMessageException(WebMessageUtils.badRequest("This key is not supported."));
    }
    File out = null;
    try {
        out = locationManager.getFileForWriting(key + ".png", "static");
    } catch (LocationManagerException e) {
        throw new WebMessageException(WebMessageUtils.error(e.getMessage()));
    }
    try {
        file.transferTo(out);
    } catch (IOException e) {
        throw new WebMessageException(WebMessageUtils.error("Could not save file."));
    }
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) IOException(java.io.IOException) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) MimeType(org.springframework.util.MimeType) LocationManagerException(org.hisp.dhis.external.location.LocationManagerException) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with WebMessageUtils.error

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

the class DataValueController method getDataValueFile.

// ---------------------------------------------------------------------
// GET file
// ---------------------------------------------------------------------
@RequestMapping(value = "/files", method = RequestMethod.GET)
public void getDataValueFile(@RequestParam String de, @RequestParam(required = false) String co, @RequestParam(required = false) String cc, @RequestParam(required = false) String cp, @RequestParam String pe, @RequestParam String ou, HttpServletResponse response, HttpServletRequest request) throws WebMessageException {
    // ---------------------------------------------------------------------
    // Input validation
    // ---------------------------------------------------------------------
    DataElement dataElement = getAndValidateDataElement(de);
    if (!dataElement.isFileType()) {
        throw new WebMessageException(WebMessageUtils.conflict("DataElement must be of type file"));
    }
    DataElementCategoryOptionCombo categoryOptionCombo = getAndValidateCategoryOptionCombo(co, false);
    DataElementCategoryOptionCombo attributeOptionCombo = getAndValidateAttributeOptionCombo(cc, cp);
    Period period = getAndValidatePeriod(pe);
    OrganisationUnit organisationUnit = getAndValidateOrganisationUnit(ou);
    // ---------------------------------------------------------------------
    // Get data value
    // ---------------------------------------------------------------------
    DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
    if (dataValue == null) {
        throw new WebMessageException(WebMessageUtils.conflict("Data value does not exist"));
    }
    // ---------------------------------------------------------------------
    // Get file resource
    // ---------------------------------------------------------------------
    String uid = dataValue.getValue();
    FileResource fileResource = fileResourceService.getFileResource(uid);
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(WebMessageUtils.notFound("A data value file resource with id " + uid + " does not exist."));
    }
    FileResourceStorageStatus storageStatus = fileResource.getStorageStatus();
    if (storageStatus != FileResourceStorageStatus.STORED) {
        // Special case:
        //  The FileResource exists and has been tied to this DataValue, however, the underlying file
        //  content is still not stored to the (most likely external) file store provider.
        // HTTP 409, for lack of a more suitable status code
        WebMessage webMessage = WebMessageUtils.conflict("The content is being processed and is not available yet. Try again later.", "The content requested is in transit to the file store and will be available at a later time.");
        webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
        throw new WebMessageException(webMessage);
    }
    ByteSource content = fileResourceService.getFileResourceContent(fileResource);
    if (content == null) {
        throw new WebMessageException(WebMessageUtils.notFound("The referenced file could not be found"));
    }
    // ---------------------------------------------------------------------
    // Attempt to build signed URL request for content and redirect
    // ---------------------------------------------------------------------
    URI signedGetUri = fileResourceService.getSignedGetFileResourceContentUri(uid);
    if (signedGetUri != null) {
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.setHeader(HttpHeaders.LOCATION, signedGetUri.toASCIIString());
        return;
    }
    // ---------------------------------------------------------------------
    // Build response and return
    // ---------------------------------------------------------------------
    response.setContentType(fileResource.getContentType());
    response.setContentLength(new Long(fileResource.getContentLength()).intValue());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    // ---------------------------------------------------------------------
    // Request signing is not available, stream content back to client
    // ---------------------------------------------------------------------
    InputStream inputStream = null;
    try {
        inputStream = content.openStream();
        IOUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException e) {
        throw new WebMessageException(WebMessageUtils.error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend. " + "Depending on the provider the root cause could be network or file system related."));
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.datavalue.DataValue) InputStream(java.io.InputStream) FileResourceStorageStatus(org.hisp.dhis.fileresource.FileResourceStorageStatus) FileResource(org.hisp.dhis.fileresource.FileResource) Period(org.hisp.dhis.period.Period) IOException(java.io.IOException) URI(java.net.URI) DataElement(org.hisp.dhis.dataelement.DataElement) FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) ByteSource(com.google.common.io.ByteSource) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with WebMessageUtils.error

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

the class FileResourceController method saveFileResource.

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public WebMessage saveFileResource(@RequestParam MultipartFile file) throws WebMessageException, IOException {
    String filename = StringUtils.defaultIfBlank(FilenameUtils.getName(file.getOriginalFilename()), DEFAULT_FILENAME);
    String contentType = file.getContentType();
    contentType = isValidContentType(contentType) ? contentType : DEFAULT_CONTENT_TYPE;
    long contentLength = file.getSize();
    if (contentLength <= 0) {
        throw new WebMessageException(WebMessageUtils.conflict("Could not read file or file is empty."));
    }
    ByteSource bytes = new MultipartFileByteSource(file);
    String contentMd5 = bytes.hash(Hashing.md5()).toString();
    FileResource fileResource = new FileResource(filename, contentType, contentLength, contentMd5, FileResourceDomain.DATA_VALUE);
    fileResource.setAssigned(false);
    fileResource.setCreated(new Date());
    fileResource.setUser(currentUserService.getCurrentUser());
    File tmpFile = toTempFile(file);
    String uid = fileResourceService.saveFileResource(fileResource, tmpFile);
    if (uid == null) {
        throw new WebMessageException(WebMessageUtils.error("Saving the file failed."));
    }
    WebMessage webMessage = new WebMessage(Status.OK, HttpStatus.ACCEPTED);
    webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
    return webMessage;
}
Also used : FileResourceWebMessageResponse(org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) FileResource(org.hisp.dhis.fileresource.FileResource) ByteSource(com.google.common.io.ByteSource) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) Date(java.util.Date) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 WebMessage (org.hisp.dhis.dxf2.webmessage.WebMessage)4 ByteSource (com.google.common.io.ByteSource)3 IOException (java.io.IOException)3 FileResourceWebMessageResponse (org.hisp.dhis.dxf2.webmessage.responses.FileResourceWebMessageResponse)3 FileResource (org.hisp.dhis.fileresource.FileResource)3 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)3 File (java.io.File)2 InputStream (java.io.InputStream)2 URI (java.net.URI)2 DataElement (org.hisp.dhis.dataelement.DataElement)2 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)2 MultipartFile (org.springframework.web.multipart.MultipartFile)2 Date (java.util.Date)1 DataElementCategoryOptionCombo (org.hisp.dhis.dataelement.DataElementCategoryOptionCombo)1 DataValue (org.hisp.dhis.datavalue.DataValue)1 DataValue (org.hisp.dhis.dxf2.events.event.DataValue)1 Event (org.hisp.dhis.dxf2.events.event.Event)1 LocationManagerException (org.hisp.dhis.external.location.LocationManagerException)1