Search in sources :

Example 1 with FieldValidationException

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

the class RestAuthenticationFailureHandler method onAuthenticationFailure.

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    FieldValidationException fve = ExceptionUtils.findExceptionOfType(exception, FieldValidationException.class);
    if (fve != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        jsonResponseHelper.writeResponseBody(new ValidationErrors(fve.getErrors()), response);
        return;
    }
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    GenericServerErrorResult responseBody = new GenericServerErrorResult(exceptionTranslator.buildUserMessage(exception, LocaleContextHolder.getLocale()), new ExceptionInfo(exception));
    jsonResponseHelper.writeResponseBody(responseBody, response);
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) ValidationErrors(org.summerb.approaches.validation.ValidationErrors) GenericServerErrorResult(org.summerb.utils.exceptions.dto.GenericServerErrorResult) ExceptionInfo(org.summerb.utils.exceptions.dto.ExceptionInfo)

Example 2 with FieldValidationException

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

the class RestExceptionTranslator method determineFailureResult.

private DtoBase determineFailureResult(Exception ex, HttpServletRequest request, HttpServletResponse response) {
    // first see if it is FVE
    FieldValidationException fve = ExceptionUtils.findExceptionOfType(ex, FieldValidationException.class);
    if (fve != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return fve.getErrorDescriptionObject();
    }
    boolean translateAuthErrors = Boolean.TRUE.equals(Boolean.valueOf(request.getHeader(X_TRANSLATE_AUTHORIZATION_ERRORS)));
    GenericServerErrorResult ret = null;
    if (translateAuthErrors) {
        ret = new GenericServerErrorResult(exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale()), new ExceptionInfo(ex));
    }
    NotAuthorizedException naex = ExceptionUtils.findExceptionOfType(ex, NotAuthorizedException.class);
    if (naex != null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : naex.getResult();
    }
    AuthenticationException ae = ExceptionUtils.findExceptionOfType(ex, AuthenticationException.class);
    if (ae != null) {
        // NOTE: See how we did that in AuthenticationFailureHandlerImpl...
        // Looks like we need to augment our custom RestLoginFilter so it
        // will put username to request
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult("(username not resolved)", SecurityMessageCodes.AUTH_FATAL);
    }
    AccessDeniedException ade = ExceptionUtils.findExceptionOfType(ex, AccessDeniedException.class);
    if (ade != null) {
        if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.ACCESS_DENIED);
    }
    CurrentUserNotFoundException cunfe = ExceptionUtils.findExceptionOfType(ex, CurrentUserNotFoundException.class);
    if (cunfe != null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
    }
    // TODO: Do we really need to send whole stack trace to client ??? I think we
    // should do it only during development
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new GenericServerErrorResult(exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale()), new ExceptionInfo(ex));
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) AuthenticationException(org.springframework.security.core.AuthenticationException) NotAuthorizedResult(org.summerb.approaches.security.api.dto.NotAuthorizedResult) CurrentUserNotFoundException(org.summerb.approaches.security.api.CurrentUserNotFoundException) NotAuthorizedException(org.summerb.approaches.security.api.exceptions.NotAuthorizedException) GenericServerErrorResult(org.summerb.utils.exceptions.dto.GenericServerErrorResult) ExceptionInfo(org.summerb.utils.exceptions.dto.ExceptionInfo)

Example 3 with FieldValidationException

use of org.summerb.approaches.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.approaches.validation.FieldValidationException) ValidationError(org.summerb.approaches.validation.ValidationError) GenericException(org.summerb.utils.exceptions.GenericException) UserNotFoundException(org.summerb.microservices.users.api.exceptions.UserNotFoundException) FieldValidationException(org.summerb.approaches.validation.FieldValidationException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with FieldValidationException

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

the class LoginController method processPasswordChangeForm.

@Secured({ "ROLE_USER" })
@RequestMapping(method = RequestMethod.POST, value = SecurityActionsUrlsProviderDefaultImpl.CHANGE_PASSWORD)
public String processPasswordChangeForm(@ModelAttribute(ATTR_PASSWORD_CHANGE) PasswordChange passwordChange, Model model, HttpServletRequest request) throws UserNotFoundException {
    try {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        usersServiceFacade.changePassword(auth.getName(), passwordChange);
        model.addAttribute(ATTR_PASSWORD_CHANGED, true);
    } catch (FieldValidationException fve) {
        model.addAttribute(ControllerBase.ATTR_VALIDATION_ERRORS, new ValidationErrorsVm(fve.getErrors()));
    }
    return views.changePassword();
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) Authentication(org.springframework.security.core.Authentication) ValidationErrorsVm(org.summerb.approaches.springmvc.model.ValidationErrorsVm) Secured(org.springframework.security.access.annotation.Secured) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with FieldValidationException

use of org.summerb.approaches.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.approaches.validation.FieldValidationException) UserNotFoundException(org.summerb.microservices.users.api.exceptions.UserNotFoundException) RegistrationAlreadyRequestedValidationError(org.summerb.approaches.springmvc.security.ve.RegistrationAlreadyRequestedValidationError) User(org.summerb.microservices.users.api.dto.User) UserServiceUnexpectedException(org.summerb.microservices.users.api.exceptions.UserServiceUnexpectedException) UserStatus(org.summerb.approaches.springmvc.security.dto.UserStatus) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

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