Search in sources :

Example 16 with FieldValidationException

use of org.summerb.approaches.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.approaches.validation.FieldValidationException) UserNotFoundException(org.summerb.microservices.users.api.exceptions.UserNotFoundException) User(org.summerb.microservices.users.api.dto.User) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PasswordInvalidValidationError(org.summerb.approaches.springmvc.security.ve.PasswordInvalidValidationError) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) UserDetailsImpl(org.summerb.approaches.springmvc.security.dto.UserDetailsImpl) InvalidPasswordException(org.summerb.microservices.users.api.exceptions.InvalidPasswordException) UserNotFoundValidationError(org.summerb.approaches.springmvc.security.ve.UserNotFoundValidationError)

Example 17 with FieldValidationException

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

the class UserDetailsServiceDefaultImpl method loadUserByUsername.

@Override
public UserDetails loadUserByUsername(String userEmail) throws UsernameNotFoundException {
    try {
        User user = userService.getUserByEmail(userEmail);
        List<String> permissions = permissionService.findUserPermissionsForSubject(SecurityConstants.DOMAIN, user.getUuid(), null);
        AuthToken authToken = null;
        UserDetailsImpl ret = new UserDetailsImpl(user, null, permissions, authToken);
        return ret;
    } catch (UserNotFoundException e) {
        throw new UsernameNotFoundException("User not found", e);
    } catch (FieldValidationException e) {
        throw new UsernameNotFoundException("Email provided in invalid format", e);
    } catch (Throwable t) {
        throw new UsernameNotFoundException("Failed to get user by email", t);
    }
}
Also used : UserDetailsImpl(org.summerb.approaches.springmvc.security.dto.UserDetailsImpl) UserNotFoundException(org.summerb.microservices.users.api.exceptions.UserNotFoundException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) FieldValidationException(org.summerb.approaches.validation.FieldValidationException) User(org.summerb.microservices.users.api.dto.User) AuthToken(org.summerb.microservices.users.api.dto.AuthToken)

Example 18 with FieldValidationException

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

the class ControllerExceptionHandlerStrategyLegacyImpl method buildJsonError.

/**
 * This peace of crap needs to be removed. Because in case of JSON it's rest
 * API, there is no place for {@link ModelAndView}. Response should be pure JSON
 * content.
 *
 * So instead of implementing it here it's better to just re-throw exception and
 * let {@link RestExceptionTranslator} handle it and gracefully convert it into
 * json description of error happened
 */
protected ModelAndView buildJsonError(Throwable ex, HttpServletRequest req, HttpServletResponse res) {
    String msg = exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale());
    NotAuthorizedException nae;
    FieldValidationException fve;
    AccessDeniedException ade;
    boolean translateAuthExc = Boolean.TRUE.equals(Boolean.valueOf(req.getHeader(RestExceptionTranslator.X_TRANSLATE_AUTHORIZATION_ERRORS)));
    if ((nae = ExceptionUtils.findExceptionOfType(ex, NotAuthorizedException.class)) != null) {
        NotAuthorizedResult naeResult = nae.getResult();
        res.setStatus(isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN);
        if (translateAuthExc) {
            return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
        } else {
            respondWithJson(naeResult, res);
            return null;
        }
    } else if ((ade = ExceptionUtils.findExceptionOfType(ex, AccessDeniedException.class)) != null) {
        res.setStatus(isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN);
        if (translateAuthExc) {
            return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
        } else {
            respondWithJson(new NotAuthorizedResult(getCurrentUser(), SecurityMessageCodes.ACCESS_DENIED), res);
            return null;
        }
    } else if ((fve = ExceptionUtils.findExceptionOfType(ex, FieldValidationException.class)) != null) {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ValidationErrorsVm vepm = new ValidationErrorsVm(fve.getErrors());
        return new ModelAndView(jsonView, ControllerBase.ATTR_VALIDATION_ERRORS, vepm.getMsg());
    }
    log.warn("Failed to process request", ex);
    res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ValidationErrorsVm(org.summerb.approaches.springmvc.model.ValidationErrorsVm) ModelAndView(org.springframework.web.servlet.ModelAndView) NotAuthorizedResult(org.summerb.approaches.security.api.dto.NotAuthorizedResult) NotAuthorizedException(org.summerb.approaches.security.api.exceptions.NotAuthorizedException)

Example 19 with FieldValidationException

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

the class LoginController method processRegisterForm.

@RequestMapping(method = RequestMethod.POST, value = SecurityActionsUrlsProviderDefaultImpl.REGISTER)
public String processRegisterForm(@ModelAttribute(ATTR_REGISTRATION) Registration registration, Model model, HttpServletRequest request) {
    if (!isAutoTestMode) {
        CaptchaController.assertCaptchaTokenValid("register", registration.getCaptcha(), request);
    }
    try {
        // Create user
        User user = usersServiceFacade.registerUser(registration);
        model.addAttribute(ATTR_REGISTERED, true);
        if (isDevMode) {
            String activationAbsoluteLink = absoluteUrlBuilder.buildExternalUrl(securityActionsUrlsProvider.buildRegistrationActivationPath(user.getUuid()));
            model.addAttribute(UserAccountChangeHadlersDefaultImpl.ATTR_ACTIVATION_LINK, activationAbsoluteLink);
        }
    } catch (FieldValidationException fve) {
        model.addAttribute(ControllerBase.ATTR_VALIDATION_ERRORS, new ValidationErrorsVm(fve.getErrors()));
    }
    return views.registerForm();
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) User(org.summerb.microservices.users.api.dto.User) ValidationErrorsVm(org.summerb.approaches.springmvc.model.ValidationErrorsVm) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 20 with FieldValidationException

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

the class UsersServiceFacadeImpl method resetPassword.

@Transactional(rollbackFor = Throwable.class)
@Override
public void resetPassword(String email, String passwordResetToken, PasswordReset resetPasswordRequest) throws UserNotFoundException, FieldValidationException {
    try {
        String userUuid = assertPasswordResetOperationValid(email, passwordResetToken, resetPasswordRequest);
        passwordService.setUserPassword(userUuid, resetPasswordRequest.getPassword());
        // generate new token in order to invalidate current
        passwordService.getNewRestorationTokenForUser(userUuid);
        // If account requires activation, do it
        if (isAccountRequiresActivation(userUuid)) {
            activateAccount(userUuid);
        }
    } catch (Throwable e) {
        Throwables.throwIfInstanceOf(e, FieldValidationException.class);
        throw new UserServiceUnexpectedException("Failed to arrange password reset", e);
    }
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) UserServiceUnexpectedException(org.summerb.microservices.users.api.exceptions.UserServiceUnexpectedException) 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