use of org.hisp.dhis.security.RestoreOptions in project dhis2-core by dhis2.
the class IsInviteTokenValidAction method execute.
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() {
userCredentials = userService.getUserCredentialsByUsername(username);
if (userCredentials == null) {
return ERROR;
}
email = userCredentials.getUserInfo().getEmail();
RestoreOptions restoreOptions = securityService.getRestoreOptions(token);
if (restoreOptions != null) {
usernameChoice = Boolean.toString(restoreOptions.isUsernameChoice());
}
String errorMessage = securityService.verifyToken(userCredentials, token, RestoreType.INVITE);
return errorMessage == null ? SUCCESS : ERROR;
}
use of org.hisp.dhis.security.RestoreOptions in project dhis2-core by dhis2.
the class UserController method resendInvite.
@RequestMapping(value = "/{id}" + INVITE_PATH, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void resendInvite(@PathVariable String id, HttpServletRequest request) throws Exception {
User user = userService.getUser(id);
if (user == null) {
throw new WebMessageException(WebMessageUtils.conflict("User not found: " + id));
}
if (user.getUserCredentials() == null || !user.getUserCredentials().isInvitation()) {
throw new WebMessageException(WebMessageUtils.conflict("User account is not an invitation: " + id));
}
String valid = securityService.validateRestore(user.getUserCredentials());
if (valid != null) {
throw new WebMessageException(WebMessageUtils.conflict(valid));
}
boolean isInviteUsername = securityService.isInviteUsername(user.getUsername());
RestoreOptions restoreOptions = isInviteUsername ? RestoreOptions.INVITE_WITH_USERNAME_CHOICE : RestoreOptions.INVITE_WITH_DEFINED_USERNAME;
securityService.sendRestoreMessage(user.getUserCredentials(), ContextUtils.getContextPath(request), restoreOptions);
}
use of org.hisp.dhis.security.RestoreOptions 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.security.RestoreOptions in project dhis2-core by dhis2.
the class AddUserAction method execute.
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() throws Exception {
if (!userService.canAddOrUpdateUser(ugSelected)) {
throw new AccessDeniedException("You cannot add this user");
}
User currentUser = currentUserService.getCurrentUser();
// ---------------------------------------------------------------------
// User credentials and user
// ---------------------------------------------------------------------
UserCredentials userCredentials = new UserCredentials();
User user = new User();
userCredentials.setUserInfo(user);
user.setUserCredentials(userCredentials);
userCredentials.setUsername(StringUtils.trimToNull(username));
userCredentials.setExternalAuth(externalAuth);
userCredentials.setOpenId(StringUtils.trimToNull(openId));
userCredentials.setLdapId(StringUtils.trimToNull(ldapId));
if (ACCOUNT_ACTION_INVITE.equals(accountAction)) {
userCredentials.setUsername(StringUtils.trimToNull(inviteUsername));
userCredentials.setInvitation(true);
user.setEmail(StringUtils.trimToNull(inviteEmail));
securityService.prepareUserForInvite(user);
} else {
user.setSurname(StringUtils.trimToNull(surname));
user.setFirstName(StringUtils.trimToNull(firstName));
user.setEmail(StringUtils.trimToNull(email));
user.setPhoneNumber(StringUtils.trimToNull(phoneNumber));
userService.encodeAndSetPassword(userCredentials, StringUtils.trimToNull(rawPassword));
}
if (jsonAttributeValues != null) {
attributeService.updateAttributeValues(user, jsonAttributeValues);
}
// ---------------------------------------------------------------------
// Organisation units
// ---------------------------------------------------------------------
Set<OrganisationUnit> dataCaptureOrgUnits = new HashSet<>(selectionManager.getSelectedOrganisationUnits());
user.updateOrganisationUnits(dataCaptureOrgUnits);
Set<OrganisationUnit> dataViewOrgUnits = new HashSet<>(selectionTreeManager.getReloadedSelectedOrganisationUnits());
user.setDataViewOrganisationUnits(dataViewOrgUnits);
if (dataViewOrgUnits.size() == 0 && currentUser.getDataViewOrganisationUnits().size() != 0) {
user.setDataViewOrganisationUnits(new HashSet<>(currentUser.getDataViewOrganisationUnits()));
}
// ---------------------------------------------------------------------
// User roles
// ---------------------------------------------------------------------
Set<UserAuthorityGroup> userAuthorityGroups = new HashSet<>();
for (String id : urSelected) {
userAuthorityGroups.add(userService.getUserAuthorityGroup(id));
}
userService.canIssueFilter(userAuthorityGroups);
userCredentials.setUserAuthorityGroups(userAuthorityGroups);
// ---------------------------------------------------------------------
// Dimension constraints. Note that any new user must inherit dimension
// constraints if any from the current user.
// ---------------------------------------------------------------------
userCredentials.setCogsDimensionConstraints(new HashSet<>(currentUser.getUserCredentials().getCogsDimensionConstraints()));
userCredentials.setCatDimensionConstraints(new HashSet<>(currentUser.getUserCredentials().getCatDimensionConstraints()));
for (String id : dcSelected) {
CategoryOptionGroupSet cogs = categoryService.getCategoryOptionGroupSet(id);
if (cogs != null) {
userCredentials.getCogsDimensionConstraints().add(cogs);
continue;
}
DataElementCategory cat = categoryService.getDataElementCategory(id);
if (cat != null) {
userCredentials.getCatDimensionConstraints().add(cat);
continue;
}
}
// ---------------------------------------------------------------------
// Add User
// ---------------------------------------------------------------------
userService.addUser(user);
userService.addUserCredentials(userCredentials);
// ---------------------------------------------------------------------
// User settings
// ---------------------------------------------------------------------
userSettingService.saveUserSetting(UserSettingKey.UI_LOCALE, LocaleUtils.getLocale(localeUi), user);
userSettingService.saveUserSetting(UserSettingKey.DB_LOCALE, LocaleUtils.getLocale(localeDb), user);
if (ACCOUNT_ACTION_INVITE.equals(accountAction)) {
RestoreOptions restoreOptions = inviteUsername == null || inviteUsername.isEmpty() ? RestoreOptions.INVITE_WITH_USERNAME_CHOICE : RestoreOptions.INVITE_WITH_DEFINED_USERNAME;
securityService.sendRestoreMessage(userCredentials, getRootPath(), restoreOptions);
}
for (String id : ugSelected) {
UserGroup userGroup = userGroupService.getUserGroup(id);
userGroup.addUser(user);
userGroupService.updateUserGroup(userGroup);
}
if (ouwtSelected != null && manager.search(OrganisationUnit.class, ouwtSelected) != null) {
selectionManager.setSelectedOrganisationUnits(Lists.newArrayList(manager.search(OrganisationUnit.class, ouwtSelected)));
} else {
selectionManager.setSelectedOrganisationUnits(currentUser.getOrganisationUnits());
}
return SUCCESS;
}
use of org.hisp.dhis.security.RestoreOptions in project dhis2-core by dhis2.
the class UserController method inviteUser.
/**
* Creates a user invitation and invites the user.
*
* @param user user object parsed from the POST request.
*/
private ObjectReport inviteUser(User user, User currentUser, HttpServletRequest request) throws Exception {
RestoreOptions restoreOptions = user.getUsername() == null || user.getUsername().isEmpty() ? RestoreOptions.INVITE_WITH_USERNAME_CHOICE : RestoreOptions.INVITE_WITH_DEFINED_USERNAME;
securityService.prepareUserForInvite(user);
ImportReport importReport = createUser(user, currentUser);
ObjectReport objectReport = getObjectReport(importReport);
if (importReport.getStatus() == Status.OK && importReport.getStats().getCreated() == 1) {
securityService.sendRestoreMessage(user.getUserCredentials(), ContextUtils.getContextPath(request), restoreOptions);
}
return objectReport;
}
Aggregations