Search in sources :

Example 1 with TwoFaKeyNotSetException

use of org.openkilda.exception.TwoFaKeyNotSetException in project open-kilda by telstra.

the class LoginController method authenticate.

/**
 * Authenticate.
 *
 * @param username the username
 * @param password the password
 * @param request the request
 * @return the model and view
 */
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ModelAndView authenticate(@RequestParam("username") String username, @RequestParam("password") final String password, final HttpServletRequest request, RedirectAttributes redir) {
    ModelAndView modelAndView = new ModelAndView(IConstants.View.LOGIN);
    String error = null;
    username = username != null ? username.toLowerCase() : null;
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    CustomWebAuthenticationDetails customWebAuthenticationDetails = new CustomWebAuthenticationDetails(request);
    token.setDetails(customWebAuthenticationDetails);
    try {
        HttpSession sessionOld = request.getSession(false);
        if (sessionOld != null && !sessionOld.isNew()) {
            sessionOld.invalidate();
        }
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate.isAuthenticated()) {
            modelAndView.setViewName(IConstants.View.REDIRECT_HOME);
            UserInfo userInfo = getLoggedInUser(request);
            userService.populateUserInfo(userInfo, username);
            request.getSession(true).setAttribute(IConstants.SESSION_OBJECT, userInfo);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            userService.updateLoginDetail(username);
        } else {
            error = "Login failed; Invalid email or password.";
            LOGGER.warn("Authentication failure for user: '" + username + "'");
            modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
        }
    } catch (TwoFaKeyNotSetException e) {
        LOGGER.warn("2 FA Key not set for user: '" + username + "'");
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        String secretKey = TwoFactorUtility.getBase32EncryptedKey();
        modelAndView.addObject("key", secretKey);
        userService.updateUser2FaKey(username, secretKey);
        modelAndView.addObject("applicationName", applicationName);
        modelAndView.setViewName(IConstants.View.TWO_FA_GENERATOR);
    } catch (OtpRequiredException e) {
        LOGGER.warn("OTP required for user: '" + username + "'");
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        modelAndView.addObject("applicationName", applicationName);
        modelAndView.setViewName(IConstants.View.OTP);
    } catch (InvalidOtpException e) {
        LOGGER.warn("Authentication code is invalid for user: '" + username + "'");
        error = "Authentication code is invalid";
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        modelAndView.addObject("applicationName", applicationName);
        if (customWebAuthenticationDetails.isConfigure2Fa()) {
            UserEntity userInfo = userService.getUserByUsername(username);
            modelAndView.addObject("key", userInfo.getTwoFaKey());
            modelAndView.setViewName(IConstants.View.TWO_FA_GENERATOR);
        } else {
            modelAndView.setViewName(IConstants.View.OTP);
        }
    } catch (BadCredentialsException e) {
        LOGGER.warn("Authentication failure", e);
        error = e.getMessage();
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    } catch (LockedException e) {
        error = e.getMessage();
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    } catch (Exception e) {
        LOGGER.warn("Authentication failure", e);
        error = "Login Failed. Error: " + e.getMessage() + ".";
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    }
    if (error != null) {
        redir.addFlashAttribute("error", error);
    }
    return modelAndView;
}
Also used : LockedException(org.springframework.security.authentication.LockedException) CustomWebAuthenticationDetails(org.openkilda.security.CustomWebAuthenticationDetails) HttpSession(javax.servlet.http.HttpSession) ModelAndView(org.springframework.web.servlet.ModelAndView) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserInfo(org.usermanagement.model.UserInfo) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) OtpRequiredException(org.openkilda.exception.OtpRequiredException) UserEntity(org.usermanagement.dao.entity.UserEntity) OtpRequiredException(org.openkilda.exception.OtpRequiredException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LockedException(org.springframework.security.authentication.LockedException) InvalidOtpException(org.openkilda.exception.InvalidOtpException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) Authentication(org.springframework.security.core.Authentication) InvalidOtpException(org.openkilda.exception.InvalidOtpException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with TwoFaKeyNotSetException

use of org.openkilda.exception.TwoFaKeyNotSetException in project open-kilda by telstra.

the class UserService method changePassword.

/**
 * Change password.
 *
 * @param userInfo the user info
 * @param userId the user id
 * @return the user info
 */
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public UserInfo changePassword(final UserInfo userInfo, final Long userId) {
    userValidator.validateChangePassword(userInfo);
    UserEntity userEntity = userRepository.findByUserId(userId);
    if (ValidatorUtil.isNull(userEntity)) {
        LOGGER.warn("User Entity not found for user(id: " + userId + ")");
        throw new RequestValidationException(messageUtil.getAttributeInvalid("user_id", userId + ""));
    }
    if (!StringUtil.matches(userInfo.getPassword(), userEntity.getPassword())) {
        LOGGER.warn("Password not matched for user (id: " + userId + "). Error: " + messageUtil.getAttributePasswordInvalid());
        throw new RequestValidationException(messageUtil.getAttributePasswordInvalid());
    }
    if (userEntity.getIs2FaEnabled()) {
        if (!userEntity.getIs2FaConfigured()) {
            LOGGER.warn("2FA key is not configured for user(id: " + userId + "). Error: " + messageUtil.getAttribute2faNotConfiured());
            throw new TwoFaKeyNotSetException(messageUtil.getAttribute2faNotConfiured());
        } else {
            if (userInfo.getCode() == null || userInfo.getCode().isEmpty()) {
                LOGGER.warn("OTP code is madatory as 2FA is configured for user (id: " + userId + "). Error: " + messageUtil.getAttributeNotNull("OTP"));
                throw new OtpRequiredException(messageUtil.getAttributeNotNull("OTP"));
            } else if (!TwoFactorUtility.validateOtp(userInfo.getCode(), userEntity.getTwoFaKey())) {
                LOGGER.warn("Invalid OTP for user (id: " + userId + "). Error: " + messageUtil.getAttributeNotvalid("OTP"));
                throw new RequestValidationException(messageUtil.getAttributeNotvalid("OTP"));
            }
        }
    }
    userEntity.setPassword(StringUtil.encodeString(userInfo.getNewPassword()));
    userEntity.setUpdatedDate(new Date());
    userEntity = userRepository.save(userEntity);
    activityLogger.log(ActivityType.CHANGE_PASSWORD, userEntity.getUsername());
    LOGGER.info("User(userId: " + userId + ") password changed successfully.");
    try {
        Map<String, Object> context = new HashMap<>();
        context.put("name", userEntity.getName());
        mailService.send(userEntity.getEmail(), mailUtils.getSubjectChangePassword(), TemplateService.Template.CHANGE_PASSWORD, context);
        LOGGER.info("Changed password mail sent successfully for user(userId: " + userId + ").");
    } catch (Exception e) {
        LOGGER.warn("Change password email failed for username: " + userEntity.getUsername());
    }
    return UserConversionUtil.toUserInfo(userEntity);
}
Also used : HashMap(java.util.HashMap) RequestValidationException(org.usermanagement.exception.RequestValidationException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) UserEntity(org.usermanagement.dao.entity.UserEntity) OtpRequiredException(org.openkilda.exception.OtpRequiredException) Date(java.util.Date) OtpRequiredException(org.openkilda.exception.OtpRequiredException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) InvalidOtpException(org.openkilda.exception.InvalidOtpException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) AccessDeniedException(java.nio.file.AccessDeniedException) RequestValidationException(org.usermanagement.exception.RequestValidationException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with TwoFaKeyNotSetException

use of org.openkilda.exception.TwoFaKeyNotSetException in project open-kilda by telstra.

the class CustomAuthenticationProvider method authenticate.

/*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.authentication.dao.
     * AbstractUserDetailsAuthenticationProvider#authenticate(org.
     * springframework.security.core.Authentication)
     */
@Override
public Authentication authenticate(final Authentication auth) throws org.springframework.security.core.AuthenticationException {
    CustomWebAuthenticationDetails customWebAuthenticationDetails = ((CustomWebAuthenticationDetails) auth.getDetails());
    String verificationCode = customWebAuthenticationDetails.getVerificationCode();
    UserEntity user = userRepository.findByUsernameIgnoreCase(auth.getName());
    if (user == null || !user.getActiveFlag()) {
        throw new BadCredentialsException("Login failed; Invalid email or password.");
    }
    String loginCount = null;
    String unlockTime = null;
    if (user.getUserId() != 1) {
        loginCount = applicationSettingService.getApplicationSetting(ApplicationSetting.INVALID_LOGIN_ATTEMPT);
        unlockTime = applicationSettingService.getApplicationSetting(ApplicationSetting.USER_ACCOUNT_UNLOCK_TIME);
        if (!user.getStatusEntity().getStatus().equalsIgnoreCase("ACTIVE")) {
            checkUserLoginAttempts(user, loginCount, unlockTime);
        }
    }
    try {
        final Authentication result = super.authenticate(auth);
        if (user.getIs2FaEnabled()) {
            if (!user.getIs2FaConfigured() && !customWebAuthenticationDetails.isConfigure2Fa()) {
                throw new TwoFaKeyNotSetException();
            } else {
                if (verificationCode == null || verificationCode.isEmpty()) {
                    throw new OtpRequiredException();
                } else if (!TwoFactorUtility.validateOtp(verificationCode, user.getTwoFaKey())) {
                    throw new InvalidOtpException("Invalid verfication code");
                }
            }
        }
        return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities());
    } catch (BadCredentialsException e) {
        String error = null;
        if (user.getUserId() != 1) {
            error = updateInvalidLoginAttempts(user, loginCount, unlockTime);
        } else {
            error = "Login Failed.Invalid email or password.";
        }
        throw new BadCredentialsException(error);
    }
}
Also used : Authentication(org.springframework.security.core.Authentication) InvalidOtpException(org.openkilda.exception.InvalidOtpException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) UserEntity(org.usermanagement.dao.entity.UserEntity) OtpRequiredException(org.openkilda.exception.OtpRequiredException)

Aggregations

InvalidOtpException (org.openkilda.exception.InvalidOtpException)3 OtpRequiredException (org.openkilda.exception.OtpRequiredException)3 TwoFaKeyNotSetException (org.openkilda.exception.TwoFaKeyNotSetException)3 UserEntity (org.usermanagement.dao.entity.UserEntity)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 Authentication (org.springframework.security.core.Authentication)2 AccessDeniedException (java.nio.file.AccessDeniedException)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 HttpSession (javax.servlet.http.HttpSession)1 CustomWebAuthenticationDetails (org.openkilda.security.CustomWebAuthenticationDetails)1 LockedException (org.springframework.security.authentication.LockedException)1 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)1 Transactional (org.springframework.transaction.annotation.Transactional)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1 ModelAndView (org.springframework.web.servlet.ModelAndView)1 RequestValidationException (org.usermanagement.exception.RequestValidationException)1 UserInfo (org.usermanagement.model.UserInfo)1