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());
}
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);
}
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;
}
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);
}
}
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);
}
Aggregations