Search in sources :

Example 6 with FieldValidationException

use of org.summerb.validation.FieldValidationException in project summerb by skarpushin.

the class PasswordServiceImpl method setUserPassword.

@Override
@Transactional(rollbackFor = Throwable.class)
public void setUserPassword(String userUuid, String newPasswordPlain) throws UserNotFoundException, FieldValidationException {
    Preconditions.checkArgument(userUuid != null);
    Preconditions.checkArgument(newPasswordPlain != null);
    assertUserExists(userUuid);
    if (!StringUtils.hasText(newPasswordPlain)) {
        throw new FieldValidationException(new FieldRequiredValidationError(FN_PASSWORD));
    }
    String newPasswordHash = null;
    try {
        newPasswordHash = encodePassword(newPasswordPlain);
        // sanity check
        if (!isPasswordMatch(newPasswordPlain, newPasswordHash)) {
            throw new RuntimeException("Password doesn't match just created hash");
        }
        // set user password
        int updateResult = passwordDao.updateUserPassword(userUuid, newPasswordHash);
        if (updateResult < 1) {
            throw new RuntimeException("updateUserPassword returned unexpected result = " + updateResult);
        }
    } catch (Throwable t) {
        String msg = String.format("Failed to set user '%s' passwordHash '%s'", userUuid, newPasswordHash);
        throw new UserServiceUnexpectedException(msg, t);
    }
}
Also used : FieldValidationException(org.summerb.validation.FieldValidationException) UserServiceUnexpectedException(org.summerb.users.api.exceptions.UserServiceUnexpectedException) FieldRequiredValidationError(org.summerb.validation.errors.FieldRequiredValidationError) Transactional(org.springframework.transaction.annotation.Transactional)

Example 7 with FieldValidationException

use of org.summerb.validation.FieldValidationException in project summerb by skarpushin.

the class LoginController method handleLoginFailed.

@RequestMapping(method = RequestMethod.GET, value = SecurityActionsUrlsProviderDefaultImpl.LOGIN_FAILED)
public String handleLoginFailed(Model model, HttpServletRequest request) {
    Exception lastException = (Exception) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    if (lastException != null) {
        log.info("Login failed due to exception", lastException);
        model.addAttribute("lastExceptionMessage", exceptionTranslatorSimplified.buildUserMessage(lastException));
        // Delete it from session to avoid excessive memory consumption
        request.getSession().removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }
    model.addAttribute("loginError", true);
    // Add validation errors
    FieldValidationException validationErrors = ExceptionUtils.findExceptionOfType(lastException, FieldValidationException.class);
    if (validationErrors != null) {
        for (ValidationError error : validationErrors.getErrors()) {
            model.addAttribute("ve_" + error.getFieldToken(), msg(error.getMessageCode(), error.getMessageArgs()));
        }
    }
    // add login failed message
    return getLoginForm(model);
}
Also used : FieldValidationException(org.summerb.validation.FieldValidationException) ValidationError(org.summerb.validation.ValidationError) UserNotFoundException(org.summerb.users.api.exceptions.UserNotFoundException) GenericException(org.summerb.utils.exceptions.GenericException) FieldValidationException(org.summerb.validation.FieldValidationException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with FieldValidationException

use of org.summerb.validation.FieldValidationException in project summerb by skarpushin.

the class AuthenticationProviderImpl method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // Ensure that all conditions apply
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
    // check we have credentials specified
    if (authentication.getCredentials() == null) {
        logger.debug("Authentication failed: no credentials provided");
        throw new BadCredentialsException(getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    // Determine user-name
    String username = (authentication.getPrincipal() == null) ? "" : authentication.getName();
    // Encode password
    String presentedPlainPassword = authentication.getCredentials().toString();
    try {
        if (loginEligibilityVerifier != null) {
            loginEligibilityVerifier.validateUserAllowedToLogin(username);
        }
        // Proceed with authentication
        // get user
        User user = userService.getUserByEmail(username);
        // check password
        if (!passwordService.isUserPasswordValid(user.getUuid(), presentedPlainPassword)) {
            throw new InvalidPasswordException();
        }
        // get user permission
        List<String> permissions = permissionService.findUserPermissionsForSubject(SecurityConstants.DOMAIN, user.getUuid(), null);
        UserDetailsImpl userDetails = new UserDetailsImpl(user, "[PASSWORD REMOVED]", permissions, null);
        UsernamePasswordAuthenticationToken ret = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
        ret.setDetails(authentication.getDetails());
        return ret;
    } catch (FieldValidationException e) {
        throw buildBadCredentialsExc(e);
    } catch (UserNotFoundException e) {
        throw buildBadCredentialsExc(new FieldValidationException(new UserNotFoundValidationError()));
    } catch (InvalidPasswordException e) {
        throw buildBadCredentialsExc(new FieldValidationException(new PasswordInvalidValidationError()));
    } catch (Throwable t) {
        throw new AuthenticationServiceException(getMessage(SecurityMessageCodes.AUTH_FATAL, "Fatal authentication exception"), t);
    }
}
Also used : FieldValidationException(org.summerb.validation.FieldValidationException) UserNotFoundException(org.summerb.users.api.exceptions.UserNotFoundException) User(org.summerb.users.api.dto.User) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PasswordInvalidValidationError(org.summerb.webappboilerplate.security.ve.PasswordInvalidValidationError) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) InvalidPasswordException(org.summerb.users.api.exceptions.InvalidPasswordException) UserNotFoundValidationError(org.summerb.webappboilerplate.security.ve.UserNotFoundValidationError)

Example 9 with FieldValidationException

use of org.summerb.validation.FieldValidationException in project summerb by skarpushin.

the class UsersServiceFacadeImpl method registerUser.

@Transactional(rollbackFor = Throwable.class)
@Override
public User registerUser(Registration registration) throws FieldValidationException {
    try {
        Preconditions.checkArgument(registration != null, "Registration param must be not null");
        // Validate display name
        validateRegistration(registration);
        // Validate user status
        UserStatus userStatus = getUserStatusByEmail(registration.getEmail());
        if (userStatus == UserStatus.AwaitingActivation) {
            throw new FieldValidationException(new RegistrationAlreadyRequestedValidationError());
        }
        // Create user
        User user = null;
        if (userStatus == UserStatus.Provisioned) {
            user = userService.getUserByEmail(registration.getEmail());
            user.setDisplayName(registration.getDisplayName());
            user.setLocale(CurrentRequestUtils.getLocale().toString());
            user.setTimeZone(TimeZone.getDefault().getID());
            userService.updateUser(user);
        } else {
            user = new User();
            user.setEmail(registration.getEmail());
            user.setDisplayName(registration.getDisplayName());
            user.setLocale(CurrentRequestUtils.getLocale().toString());
            user.setTimeZone(TimeZone.getDefault().getID());
            user = userService.createUser(user);
        }
        // Create password
        passwordService.setUserPassword(user.getUuid(), registration.getPassword());
        // Create user account permissions
        permissionService.grantPermission(SecurityConstants.DOMAIN, user.getUuid(), null, SecurityConstants.MARKER_AWAITING_ACTIVATION);
        runUserRegisteredHandler(user);
        // 
        return user;
    } catch (UserNotFoundException e) {
        throw new UserServiceUnexpectedException("User was just created, but not found", e);
    } catch (Throwable t) {
        Throwables.throwIfInstanceOf(t, FieldValidationException.class);
        throw new RuntimeException("Unexpected error while registering user", t);
    }
}
Also used : FieldValidationException(org.summerb.validation.FieldValidationException) UserNotFoundException(org.summerb.users.api.exceptions.UserNotFoundException) RegistrationAlreadyRequestedValidationError(org.summerb.webappboilerplate.security.ve.RegistrationAlreadyRequestedValidationError) User(org.summerb.users.api.dto.User) UserServiceUnexpectedException(org.summerb.users.api.exceptions.UserServiceUnexpectedException) UserStatus(org.summerb.webappboilerplate.security.dto.UserStatus) Transactional(org.springframework.transaction.annotation.Transactional)

Example 10 with FieldValidationException

use of org.summerb.validation.FieldValidationException in project summerb by skarpushin.

the class UsersServiceFacadeImpl method getNewPasswordResetToken.

@Transactional(rollbackFor = Throwable.class)
@Override
public String getNewPasswordResetToken(String email) throws FieldValidationException {
    try {
        validateUserIsEligableForPasswordReset(email);
        User user = userService.getUserByEmail(email);
        String passwordResetToken = passwordService.getNewRestorationTokenForUser(user.getUuid());
        if (passwordResetArmedHandler != null) {
            passwordResetArmedHandler.onPasswordResetRequested(user, passwordResetToken);
        }
        return passwordResetToken;
    } catch (Throwable e) {
        Throwables.throwIfInstanceOf(e, FieldValidationException.class);
        throw new UserServiceUnexpectedException("Failed to arrange password reset", e);
    }
}
Also used : FieldValidationException(org.summerb.validation.FieldValidationException) User(org.summerb.users.api.dto.User) UserServiceUnexpectedException(org.summerb.users.api.exceptions.UserServiceUnexpectedException) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

FieldValidationException (org.summerb.validation.FieldValidationException)27 User (org.summerb.users.api.dto.User)11 UserServiceUnexpectedException (org.summerb.users.api.exceptions.UserServiceUnexpectedException)11 Transactional (org.springframework.transaction.annotation.Transactional)9 UserNotFoundException (org.summerb.users.api.exceptions.UserNotFoundException)8 ValidationContext (org.summerb.validation.ValidationContext)4 DuplicateKeyException (org.springframework.dao.DuplicateKeyException)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 AuthToken (org.summerb.users.api.dto.AuthToken)3 InvalidPasswordException (org.summerb.users.api.exceptions.InvalidPasswordException)3 ValidationError (org.summerb.validation.ValidationError)3 ValidationErrorsVm (org.summerb.webappboilerplate.model.ValidationErrorsVm)3 AccessDeniedException (org.springframework.security.access.AccessDeniedException)2 NotAuthorizedResult (org.summerb.security.api.dto.NotAuthorizedResult)2 NotAuthorizedException (org.summerb.security.api.exceptions.NotAuthorizedException)2 DuplicateUserValidationError (org.summerb.users.api.validation.DuplicateUserValidationError)2 GenericException (org.summerb.utils.exceptions.GenericException)2 ExceptionInfo (org.summerb.utils.exceptions.dto.ExceptionInfo)2 GenericServerErrorResult (org.summerb.utils.exceptions.dto.GenericServerErrorResult)2 UserStatus (org.summerb.webappboilerplate.security.dto.UserStatus)2