use of org.hisp.dhis.user.PasswordValidationResult in project dhis2-core by dhis2.
the class ValidateUserAction method execute.
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() throws Exception {
if (username != null) {
UserCredentials match = userService.getUserCredentialsByUsername(username);
if (match != null && (id == null || match.getId() != id)) {
message = i18n.getString("username_in_use");
return ERROR;
}
}
if (openId != null) {
UserCredentials match = userService.getUserCredentialsByOpenId(openId);
if (match != null && (id == null || match.getId() != id)) {
message = i18n.getString("openid_in_use");
return ERROR;
}
}
if (ldapId != null) {
UserCredentials match = userService.getUserCredentialsByLdapId(ldapId);
if (match != null && (id == null || match.getId() != id)) {
message = i18n.getString("ldap_in_use");
return ERROR;
}
}
if (inviteUsername != null) {
UserCredentials match = userService.getUserCredentialsByUsername(inviteUsername);
if (match != null && (id == null || match.getId() != id)) {
message = i18n.getString("username_in_use");
return ERROR;
}
}
if (rawPassword != null && !rawPassword.isEmpty()) {
PasswordValidationResult result;
CredentialsInfo credentialsInfo = new CredentialsInfo(username, rawPassword, email, true);
if (id != null) {
User user = userService.getUser(id);
if (user != null) {
credentialsInfo = new CredentialsInfo(user.getUsername(), rawPassword, user.getEmail(), false);
}
}
result = passwordValidationService.validate(credentialsInfo);
if (!result.isValid()) {
message = i18n.getString(result.getI18ErrorMessage());
return ERROR;
}
}
message = i18n.getString("everything_is_ok");
return SUCCESS;
}
use of org.hisp.dhis.user.PasswordValidationResult in project dhis2-core by dhis2.
the class AccountController method validatePassword.
private Map<String, String> validatePassword(String password) {
CredentialsInfo credentialsInfo = new CredentialsInfo(password, true);
PasswordValidationResult passwordValidationResult = passwordValidationService.validate(credentialsInfo);
// Custom code required because of our hacked jQuery validation
Map<String, String> result = new HashMap<>();
result.put("response", passwordValidationResult.isValid() ? "success" : "error");
result.put("message", passwordValidationResult.isValid() ? "" : passwordValidationResult.getErrorMessage());
return result;
}
use of org.hisp.dhis.user.PasswordValidationResult in project dhis2-core by dhis2.
the class MeController method validatePasswordInternal.
private RootNode validatePasswordInternal(String password, User currentUser) throws WebMessageException {
if (password == null) {
throw new WebMessageException(conflict("Required attribute 'password' missing or null."));
}
CredentialsInfo credentialsInfo = new CredentialsInfo(currentUser.getUsername(), password, currentUser.getEmail(), false);
PasswordValidationResult result = passwordValidationService.validate(credentialsInfo);
RootNode rootNode = NodeUtils.createRootNode("response");
rootNode.addChild(new SimpleNode("isValidPassword", result.isValid()));
if (!result.isValid()) {
rootNode.addChild(new SimpleNode("errorMessage", result.getErrorMessage()));
}
return rootNode;
}
use of org.hisp.dhis.user.PasswordValidationResult in project dhis2-core by dhis2.
the class AccountController method createAccount.
@PostMapping
@ResponseBody
public WebMessage 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(value = "g-recaptcha-response", required = false) String recapResponse, HttpServletRequest request) throws IOException {
User user = null;
String restoreToken = null;
boolean invitedByEmail = (inviteUsername != null && !inviteUsername.isEmpty());
boolean canChooseUsername = true;
if (invitedByEmail) {
String[] idAndRestoreToken = securityService.decodeEncodedTokens(inviteToken);
String idToken = idAndRestoreToken[0];
restoreToken = idAndRestoreToken[1];
user = userService.getUserByIdToken(idToken);
if (user == null) {
return badRequest("Invitation link not valid");
}
boolean canRestore = securityService.canRestore(user, restoreToken, RestoreType.INVITE);
if (!canRestore) {
return badRequest("Invitation code not valid");
}
RestoreOptions restoreOptions = securityService.getRestoreOptions(restoreToken);
canChooseUsername = restoreOptions.isUsernameChoice();
if (!email.equals(user.getEmail())) {
return badRequest("Email don't match invited email");
}
} else {
boolean allowed = configurationService.getConfiguration().selfRegistrationAllowed();
if (!allowed) {
return 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);
recapResponse = StringUtils.trimToNull(recapResponse);
CredentialsInfo credentialsInfo = new CredentialsInfo(username, password, email, true);
if (username == null || username.trim().length() > MAX_LENGTH) {
return badRequest("User name is not specified or invalid");
}
User usernameAlreadyTakenCredentials = userService.getUserByUsername(username);
if (canChooseUsername && usernameAlreadyTakenCredentials != null) {
return badRequest("User name is already taken");
}
if (firstName == null || firstName.trim().length() > MAX_LENGTH) {
return badRequest("First name is not specified or invalid");
}
if (surname == null || surname.trim().length() > MAX_LENGTH) {
return badRequest("Last name is not specified or invalid");
}
if (password == null) {
return badRequest("Password is not specified");
}
PasswordValidationResult result = passwordValidationService.validate(credentialsInfo);
if (!result.isValid()) {
return badRequest(result.getErrorMessage());
}
if (email == null || !ValidationUtils.emailIsValid(email)) {
return badRequest("Email is not specified or invalid");
}
if (phoneNumber == null || phoneNumber.trim().length() > MAX_PHONE_NO_LENGTH) {
return badRequest("Phone number is not specified or invalid");
}
if (employer == null || employer.trim().length() > MAX_LENGTH) {
return badRequest("Employer is not specified or invalid");
}
if (!systemSettingManager.selfRegistrationNoRecaptcha()) {
if (recapResponse == null) {
return badRequest("Please verify that you are not a robot");
}
// ---------------------------------------------------------------------
// Check result from API, return 500 if validation failed
// ---------------------------------------------------------------------
RecaptchaResponse recaptchaResponse = securityService.verifyRecaptcha(recapResponse, request.getRemoteAddr());
if (!recaptchaResponse.success()) {
log.warn("Recaptcha validation failed: " + recaptchaResponse.getErrorCodes());
return badRequest("Recaptcha validation failed: " + recaptchaResponse.getErrorCodes());
}
}
if (invitedByEmail) {
boolean restored = securityService.restore(user, restoreToken, password, RestoreType.INVITE);
if (!restored) {
log.info("Invite restore failed for: " + inviteUsername);
return badRequest("Unable to create invited user account");
}
user = new User();
user.setFirstName(firstName);
user.setSurname(surname);
user.setEmail(email);
user.setPhoneNumber(phoneNumber);
user.setEmployer(employer);
if (canChooseUsername) {
user.setUsername(username);
} else {
username = user.getUsername();
}
userService.encodeAndSetPassword(user, password);
userService.updateUser(user);
log.info("User " + username + " accepted invitation for " + inviteUsername);
} else {
UserAuthorityGroup userRole = configurationService.getConfiguration().getSelfRegistrationRole();
OrganisationUnit orgUnit = configurationService.getConfiguration().getSelfRegistrationOrgUnit();
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);
user.setUsername(username);
userService.encodeAndSetPassword(user, password);
user.setSelfRegistered(true);
user.getUserAuthorityGroups().add(userRole);
userService.addUser(user);
log.info("Created user with username: " + username);
}
Set<GrantedAuthority> authorities = getAuthorities(user.getUserAuthorityGroups());
authenticate(username, password, authorities, request);
return ok("Account created");
}
use of org.hisp.dhis.user.PasswordValidationResult in project dhis2-core by dhis2.
the class AccountController method updatePassword.
@PostMapping("/password")
public ResponseEntity<Map<String, String>> updatePassword(@RequestParam String oldPassword, @RequestParam String password, @CurrentUser User user, HttpServletRequest request) {
Map<String, String> result = new HashMap<>();
String username = user.getUsername();
if (username == null) {
result.put("status", "NON_EXPIRED");
result.put("message", "Username is not valid, redirecting to login.");
return ResponseEntity.badRequest().cacheControl(noStore()).body(result);
}
CredentialsInfo credentialsInfo = new CredentialsInfo(user.getUsername(), password, user.getEmail(), false);
if (userService.userNonExpired(user)) {
result.put("status", "NON_EXPIRED");
result.put("message", "Account is not expired, redirecting to login.");
return ResponseEntity.badRequest().cacheControl(noStore()).body(result);
}
if (!passwordManager.matches(oldPassword, user.getPassword())) {
result.put("status", "NON_MATCHING_PASSWORD");
result.put("message", "Old password is wrong, please correct and try again.");
return ResponseEntity.badRequest().cacheControl(noStore()).body(result);
}
PasswordValidationResult passwordValidationResult = passwordValidationService.validate(credentialsInfo);
if (!passwordValidationResult.isValid()) {
result.put("status", "PASSWORD_INVALID");
result.put("message", passwordValidationResult.getErrorMessage());
return ResponseEntity.badRequest().cacheControl(noStore()).body(result);
}
if (password.trim().equals(username.trim())) {
result.put("status", "PASSWORD_EQUAL_TO_USERNAME");
result.put("message", "Password cannot be equal to username");
return ResponseEntity.badRequest().cacheControl(noStore()).body(result);
}
userService.encodeAndSetPassword(user, password);
userService.updateUser(user);
authenticate(username, password, getAuthorities(user.getUserAuthorityGroups()), request);
result.put("status", "OK");
result.put("message", "Account was updated.");
return ResponseEntity.ok().cacheControl(noStore()).body(result);
}
Aggregations