Search in sources :

Example 6 with WebMessageUtils.ok

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

the class SystemSoftwareUpdateNotifyController method checkSystemUpdate.

@GetMapping(SystemSoftwareUpdateNotifyController.RESOURCE_PATH)
@ResponseBody
public WebMessage checkSystemUpdate(@RequestParam(value = "forceVersion", required = false) String forceVersion) throws Exception {
    Semver currentVersion = SystemUpdateService.getCurrentVersion();
    if (forceVersion != null) {
        currentVersion = new Semver(forceVersion);
    }
    Map<Semver, Map<String, String>> newerVersions = SystemUpdateService.getLatestNewerThan(currentVersion);
    systemUpdateService.sendMessageForEachVersion(newerVersions);
    WebMessage ok = WebMessageUtils.ok();
    ok.setResponse(new SoftwareUpdateResponse(newerVersions));
    return ok;
}
Also used : Semver(com.vdurmont.semver4j.Semver) Map(java.util.Map) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 7 with WebMessageUtils.ok

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

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

the class MaintenanceController method pruneDataByDataElement.

@RequestMapping(value = "/dataPruning/dataElements/{uid}", method = { RequestMethod.PUT, RequestMethod.POST })
@PreAuthorize("hasRole('ALL')")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void pruneDataByDataElement(@PathVariable String uid, HttpServletResponse response) throws Exception {
    DataElement dataElement = dataElementService.getDataElement(uid);
    if (dataElement == null) {
        webMessageService.sendJson(WebMessageUtils.conflict("Data element does not exist: " + uid), response);
        return;
    }
    boolean result = maintenanceService.pruneData(dataElement);
    WebMessage message = result ? WebMessageUtils.ok("Data was pruned successfully") : WebMessageUtils.conflict("Data could not be pruned");
    webMessageService.sendJson(message, response);
}
Also used : DataElement(org.hisp.dhis.dataelement.DataElement) 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 9 with WebMessageUtils.ok

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

the class MaintenanceController method pruneDataByOrganisationUnit.

@RequestMapping(value = "/dataPruning/organisationUnits/{uid}", method = { RequestMethod.PUT, RequestMethod.POST })
@PreAuthorize("hasRole('ALL')")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void pruneDataByOrganisationUnit(@PathVariable String uid, HttpServletResponse response) throws Exception {
    OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(uid);
    if (organisationUnit == null) {
        webMessageService.sendJson(WebMessageUtils.conflict("Organisation unit does not exist: " + uid), response);
        return;
    }
    boolean result = maintenanceService.pruneData(organisationUnit);
    WebMessage message = result ? WebMessageUtils.ok("Data was pruned successfully") : WebMessageUtils.conflict("Data could not be pruned");
    webMessageService.sendJson(message, response);
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) 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 10 with WebMessageUtils.ok

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

the class MinMaxDataElementController method deleteObject.

//--------------------------------------------------------------------------
// DELETE
//--------------------------------------------------------------------------
@RequestMapping(method = RequestMethod.DELETE, consumes = "application/json")
@PreAuthorize("hasRole('ALL') or hasRole('F_MINMAX_DATAELEMENT_DELETE')")
public void deleteObject(HttpServletRequest request, HttpServletResponse response) throws Exception {
    MinMaxDataElement minMax = renderService.fromJson(request.getInputStream(), MinMaxDataElement.class);
    validate(minMax);
    minMax = getReferences(minMax);
    MinMaxDataElement persisted = minMaxService.getMinMaxDataElement(minMax.getSource(), minMax.getDataElement(), minMax.getOptionCombo());
    if (Objects.isNull(persisted)) {
        throw new WebMessageException(WebMessageUtils.notFound("Can not find MinMaxDataElement."));
    }
    minMaxService.deleteMinMaxDataElement(persisted);
    webMessageService.send(WebMessageUtils.ok("MinMaxDataElement deleted."), response, request);
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) MinMaxDataElement(org.hisp.dhis.minmax.MinMaxDataElement) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

RequestMapping (org.springframework.web.bind.annotation.RequestMapping)19 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)17 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)9 Dashboard (org.hisp.dhis.dashboard.Dashboard)3 WebMessage (org.hisp.dhis.dxf2.webmessage.WebMessage)3 UpdateAccessDeniedException (org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException)3 InputStream (java.io.InputStream)2 Serializable (java.io.Serializable)2 DashboardItem (org.hisp.dhis.dashboard.DashboardItem)2 Event (org.hisp.dhis.dxf2.events.event.Event)2 KeyJsonValue (org.hisp.dhis.keyjsonvalue.KeyJsonValue)2 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)2 BulkSmsGatewayConfig (org.hisp.dhis.sms.config.BulkSmsGatewayConfig)2 SmsGatewayConfig (org.hisp.dhis.sms.config.SmsGatewayConfig)2 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)2 Semver (com.vdurmont.semver4j.Semver)1 Map (java.util.Map)1 BaseIdentifiableObject (org.hisp.dhis.common.BaseIdentifiableObject)1 DataElement (org.hisp.dhis.dataelement.DataElement)1 MinMaxDataElement (org.hisp.dhis.minmax.MinMaxDataElement)1