Search in sources :

Example 16 with CREATED

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.CREATED in project dhis2-core by dhis2.

the class MessageConversationController method postObject.

private WebMessage postObject(HttpServletRequest request, MessageConversation messageConversation) throws WebMessageException {
    Set<User> users = Sets.newHashSet(messageConversation.getUsers());
    messageConversation.getUsers().clear();
    messageConversation.getUsers().addAll(getUsersToMessageConversation(messageConversation, users));
    if (messageConversation.getUsers().isEmpty()) {
        throw new WebMessageException(conflict("No recipients selected."));
    }
    String metaData = MessageService.META_USER_AGENT + request.getHeader(ContextUtils.HEADER_USER_AGENT);
    Set<FileResource> attachments = new HashSet<>();
    for (FileResource fr : messageConversation.getAttachments()) {
        FileResource fileResource = fileResourceService.getFileResource(fr.getUid());
        if (fileResource == null) {
            throw new WebMessageException(conflict("Attachment '" + fr.getUid() + "' not found."));
        }
        if (!fileResource.getDomain().equals(FileResourceDomain.MESSAGE_ATTACHMENT) || fileResource.isAssigned()) {
            throw new WebMessageException(conflict("Attachment '" + fr.getUid() + "' is already used or not a valid attachment."));
        }
        fileResource.setAssigned(true);
        fileResourceService.updateFileResource(fileResource);
        attachments.add(fileResource);
    }
    long id = messageService.sendPrivateMessage(messageConversation.getUsers(), messageConversation.getSubject(), messageConversation.getText(), metaData, attachments);
    org.hisp.dhis.message.MessageConversation conversation = messageService.getMessageConversation(id);
    return created("Message conversation created").setLocation(MessageConversationSchemaDescriptor.API_ENDPOINT + "/" + conversation.getUid());
}
Also used : CurrentUser(org.hisp.dhis.user.CurrentUser) User(org.hisp.dhis.user.User) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) FileResource(org.hisp.dhis.fileresource.FileResource) HashSet(java.util.HashSet)

Example 17 with CREATED

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.CREATED 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 18 with CREATED

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.CREATED in project dhis2-core by dhis2.

the class UserController method validateInviteUser.

/**
     * Validates whether a user can be invited / created.
     *
     * @param user the user.
     */
private boolean validateInviteUser(User user, User currentUser) throws WebMessageException {
    if (!validateCreateUser(user, currentUser)) {
        return false;
    }
    UserCredentials credentials = user.getUserCredentials();
    if (credentials == null) {
        throw new WebMessageException(WebMessageUtils.conflict("User credentials is not present"));
    }
    credentials.setUserInfo(user);
    String valid = securityService.validateInvite(user.getUserCredentials());
    if (valid != null) {
        throw new WebMessageException(WebMessageUtils.conflict(valid + ": " + user.getUserCredentials()));
    }
    return true;
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UserCredentials(org.hisp.dhis.user.UserCredentials)

Example 19 with CREATED

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.CREATED in project dhis2-core by dhis2.

the class LockExceptionController method addLockException.

@RequestMapping(method = RequestMethod.POST)
public void addLockException(@RequestParam("ou") String organisationUnitId, @RequestParam("pe") String periodId, @RequestParam("ds") String dataSetId, HttpServletRequest request, HttpServletResponse response) throws WebMessageException {
    User user = userService.getCurrentUser();
    DataSet dataSet = dataSetService.getDataSet(dataSetId);
    Period period = periodService.reloadPeriod(PeriodType.getPeriodFromIsoString(periodId));
    if (dataSet == null || period == null) {
        throw new WebMessageException(WebMessageUtils.conflict(" DataSet or Period is invalid"));
    }
    if (!aclService.canUpdate(user, dataSet)) {
        throw new ReadAccessDeniedException("You don't have the proper permissions to update this object");
    }
    boolean created = false;
    List<String> listOrgUnitIds = new ArrayList<>();
    if (organisationUnitId.startsWith("[") && organisationUnitId.endsWith("]")) {
        String[] arrOrgUnitIds = organisationUnitId.substring(1, organisationUnitId.length() - 1).split(",");
        Collections.addAll(listOrgUnitIds, arrOrgUnitIds);
    } else {
        listOrgUnitIds.add(organisationUnitId);
    }
    if (listOrgUnitIds.size() == 0) {
        throw new WebMessageException(WebMessageUtils.conflict(" OrganisationUnit ID is invalid."));
    }
    for (String id : listOrgUnitIds) {
        OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(id);
        if (organisationUnit == null) {
            throw new WebMessageException(WebMessageUtils.conflict("Can't find OrganisationUnit with id =" + id));
        }
        if (organisationUnit.getDataSets().contains(dataSet)) {
            LockException lockException = new LockException();
            lockException.setOrganisationUnit(organisationUnit);
            lockException.setDataSet(dataSet);
            lockException.setPeriod(period);
            dataSetService.addLockException(lockException);
            created = true;
        }
    }
    if (created) {
        webMessageService.send(WebMessageUtils.created("LockException created successfully."), response, request);
    }
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) User(org.hisp.dhis.user.User) DataSet(org.hisp.dhis.dataset.DataSet) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) LockException(org.hisp.dhis.dataset.LockException) ArrayList(java.util.ArrayList) Period(org.hisp.dhis.period.Period) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 20 with CREATED

use of org.hisp.dhis.dxf2.events.trackedentity.store.query.EventQuery.COLUMNS.CREATED in project dhis2-core by dhis2.

the class KeyJsonValueController method addKeyJsonValue.

/**
     * Creates a new KeyJsonValue Object on the given namespace with the key and value supplied.
     */
@RequestMapping(value = "/{namespace}/{key}", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public void addKeyJsonValue(@PathVariable String namespace, @PathVariable String key, @RequestBody String body, @RequestParam(defaultValue = "false") boolean encrypt, HttpServletResponse response) throws IOException, WebMessageException {
    if (!hasAccess(namespace)) {
        throw new WebMessageException(WebMessageUtils.forbidden("The namespace '" + namespace + "' is protected, and you don't have the right authority to access it."));
    }
    if (keyJsonValueService.getKeyJsonValue(namespace, key) != null) {
        throw new WebMessageException(WebMessageUtils.conflict("The key '" + key + "' already exists on the namespace '" + namespace + "'."));
    }
    if (!renderService.isValidJson(body)) {
        throw new WebMessageException(WebMessageUtils.badRequest("The data is not valid JSON."));
    }
    KeyJsonValue keyJsonValue = new KeyJsonValue();
    keyJsonValue.setKey(key);
    keyJsonValue.setNamespace(namespace);
    keyJsonValue.setValue(body);
    keyJsonValue.setEncrypted(encrypt);
    keyJsonValueService.addKeyJsonValue(keyJsonValue);
    response.setStatus(HttpServletResponse.SC_CREATED);
    messageService.sendJson(WebMessageUtils.created("Key '" + key + "' created."), response);
}
Also used : KeyJsonValue(org.hisp.dhis.keyjsonvalue.KeyJsonValue) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)12 Test (org.junit.jupiter.api.Test)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 ArrayList (java.util.ArrayList)8 MetadataVersion (org.hisp.dhis.metadata.version.MetadataVersion)7 Date (java.util.Date)6 ImportSummaries (org.hisp.dhis.dxf2.importsummary.ImportSummaries)6 ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)6 AvailabilityStatus (org.hisp.dhis.dxf2.synch.AvailabilityStatus)6 DhisHttpResponse (org.hisp.dhis.system.util.DhisHttpResponse)6 HttpUtils (org.hisp.dhis.system.util.HttpUtils)6 User (org.hisp.dhis.user.User)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 List (java.util.List)5 Map (java.util.Map)5 TransactionalIntegrationTest (org.hisp.dhis.TransactionalIntegrationTest)4 Event (org.hisp.dhis.dxf2.events.event.Event)4 HashMap (java.util.HashMap)3