Search in sources :

Example 1 with RecaptchaResponse

use of org.hisp.dhis.security.RecaptchaResponse 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");
}
Also used : RestoreOptions(org.hisp.dhis.security.RestoreOptions) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) CurrentUser(org.hisp.dhis.user.CurrentUser) User(org.hisp.dhis.user.User) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) CredentialsInfo(org.hisp.dhis.user.CredentialsInfo) PasswordValidationResult(org.hisp.dhis.user.PasswordValidationResult) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) RecaptchaResponse(org.hisp.dhis.security.RecaptchaResponse) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)1 RecaptchaResponse (org.hisp.dhis.security.RecaptchaResponse)1 RestoreOptions (org.hisp.dhis.security.RestoreOptions)1 CredentialsInfo (org.hisp.dhis.user.CredentialsInfo)1 CurrentUser (org.hisp.dhis.user.CurrentUser)1 PasswordValidationResult (org.hisp.dhis.user.PasswordValidationResult)1 User (org.hisp.dhis.user.User)1 UserAuthorityGroup (org.hisp.dhis.user.UserAuthorityGroup)1 GrantedAuthority (org.springframework.security.core.GrantedAuthority)1 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)1 PostMapping (org.springframework.web.bind.annotation.PostMapping)1 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)1