easycare.web.password.ChangePasswordController.java Source code

Java tutorial

Introduction

Here is the source code for easycare.web.password.ChangePasswordController.java

Source

package easycare.web.password;

import static easycare.web.password.PasswordTokenController.LOGOUT_AFTER_PASSWORD_CHANGE_KEY;
import static easycare.web.password.PasswordTokenController.USER_PASSWORD_TOKEN_ID_KEY;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import easycare.model.User;
import easycare.model.UserPasswordToken;
import easycare.service.ApplicationSettings;
import easycare.service.ContentResourcesService;
import easycare.service.SessionSecurityService;
import easycare.service.UserPasswordService;
import easycare.service.UserService;
import easycare.web.filter.FlashScope;

@Controller
public class ChangePasswordController {
    private static final Logger log = LoggerFactory.getLogger(ChangePasswordController.class);

    public static final String FIRST_CHANGE_PASSWORD_URL = "/firstChangePassword";
    public static final String FIRST_CHANGE_PASSWORD_VIEW = "first-change-password";
    public static final String RESET_CHANGE_PASSWORD_URL = "/resetChangePassword";
    public static final String RESET_CHANGE_PASSWORD_VIEW = "reset-change-password";
    public static final String LICENSE_AGREEMENT_URL = "/licenseAgreement";
    public static final String LOGIN_USE_NEW_PASSWORD_MESSAGE = "login.use.new.password.message";
    public static final String INVALID_TOKEN_VIEW = "invalid-password-token";

    private static final String LICENSE_AGREEMENT_VIEW = "license-agreement";
    private static final String LICENSE_AGREEMENT_PROPERTY = "license.agreement";
    private static final String LICENSE_AGREEMENT = "licenseAgreement";

    @Autowired
    private ContentResourcesService contentResourcesService;

    @Autowired
    private SessionSecurityService sessionSecurityService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserPasswordService userPasswordService;

    @Autowired
    private ApplicationSettings applicationSettings;

    @Autowired
    private FlashScope flashScope;

    @ModelAttribute
    protected ChangePasswordForm initChangePasswordForm() {
        ChangePasswordForm form = new ChangePasswordForm();
        String username = sessionSecurityService.getCurrentUser().getUsername();
        form.setUsername(username);
        return form;
    }

    @RequestMapping(value = FIRST_CHANGE_PASSWORD_URL, method = RequestMethod.GET)
    public ModelAndView firstChangePasswordGet() {
        return this.changePasswordGet(FIRST_CHANGE_PASSWORD_VIEW);
    }

    @RequestMapping(value = RESET_CHANGE_PASSWORD_URL, method = RequestMethod.GET)
    public ModelAndView resetChangePasswordGet() {
        return this.changePasswordGet(RESET_CHANGE_PASSWORD_VIEW);
    }

    private ModelAndView changePasswordGet(String view) {
        ModelAndView mav = new ModelAndView(view);
        User user = this.sessionSecurityService.getCurrentUser();
        ChangePasswordForm changePasswordForm = new ChangePasswordForm();
        changePasswordForm.setUsername(user.getUsername());
        mav.addObject("changePasswordForm", changePasswordForm);
        mav.addObject("isLicenseAgreementAccepted", user.isLicenseAgreementAccepted());
        return mav;
    }

    @RequestMapping(value = FIRST_CHANGE_PASSWORD_URL, method = RequestMethod.POST)
    public ModelAndView firstChangePasswordPost(HttpServletRequest request, HttpSession session,
            @ModelAttribute("changePasswordForm") @Valid ChangePasswordForm changePasswordForm,
            BindingResult result) {
        return changePassword(request, session, changePasswordForm, result, FIRST_CHANGE_PASSWORD_VIEW);
    }

    @RequestMapping(value = RESET_CHANGE_PASSWORD_URL, method = RequestMethod.POST)
    public ModelAndView resetChangePasswordPost(HttpServletRequest request, HttpSession session,
            @ModelAttribute("changePasswordForm") @Valid ChangePasswordForm changePasswordForm,
            BindingResult result) {
        return changePassword(request, session, changePasswordForm, result, RESET_CHANGE_PASSWORD_VIEW);
    }

    protected ModelAndView changePassword(HttpServletRequest request, HttpSession session,
            ChangePasswordForm changePasswordForm, BindingResult result, String view) {
        User user = this.sessionSecurityService.getCurrentUser();

        boolean validPassword = true;
        if (!result.hasErrors()) {
            // Check Password history
            if (userService.hasUsedPassword(user, changePasswordForm.getPassword())) {
                result.rejectValue("password", "password.change.history.error");
                validPassword = false;
                userPasswordService.fireChangePasswordFailAlreadyUsedEvent(changePasswordForm.getUsername());
            }
        }

        if (result.hasErrors() || !validPassword) {
            // If password is in error, add the message code to be displayed
            ModelAndView mav = new ModelAndView(view);
            mav.addObject("changePasswordBean", changePasswordForm);
            if (!validPassword) {
                result.reject("password.change.fail");
            } else {
                userPasswordService.fireChangePasswordFailValidationEvent(changePasswordForm.getUsername(), result);
            }
            return mav;
        }

        // Update password token
        if (!updatePasswordToken(session)) {
            return new ModelAndView(INVALID_TOKEN_VIEW);
        }

        // Update user password
        user = userService.changePassword(user, changePasswordForm.getPassword());
        userPasswordService.fireChangePasswordSuccessfulEvent(changePasswordForm.getUsername());

        if (BooleanUtils.isTrue((Boolean) session.getAttribute(LOGOUT_AFTER_PASSWORD_CHANGE_KEY))) {
            return forceRelogin(request, user);
        }

        // Redirect to License Agreement page if needed
        if (!user.isLicenseAgreementAccepted()) {
            return new ModelAndView(new RedirectView("/licenseAgreement", true));
        }
        // Refresh User authorities
        sessionSecurityService.refreshUserContext(request, user, null);
        // Redirect to Home page
        return new ModelAndView(new RedirectView("/", true));
    }

    private boolean updatePasswordToken(HttpSession session) {
        String tokenKey = (String) session.getAttribute(USER_PASSWORD_TOKEN_ID_KEY);
        if (tokenKey != null) {
            UserPasswordToken token = userPasswordService.findUserPasswordToken(tokenKey);
            if (!userPasswordService.isTokenValid(token)) {
                return false;
            }
            userPasswordService.usePasswordToken(token);
            session.removeAttribute(USER_PASSWORD_TOKEN_ID_KEY);
        }
        return true;
    }

    private ModelAndView forceRelogin(HttpServletRequest request, User user) {
        sessionSecurityService.unauthenticateUser(request, user);
        flashScope.addMessage(LOGIN_USE_NEW_PASSWORD_MESSAGE);
        return new ModelAndView(new RedirectView("/login", true));
    }

    @RequestMapping(value = LICENSE_AGREEMENT_URL, method = RequestMethod.GET)
    public ModelAndView licenseAgreementGet() {

        ModelAndView mav = new ModelAndView(LICENSE_AGREEMENT_VIEW);

        try {

            String licenseAgreementFileName = contentResourcesService.getProperty(LICENSE_AGREEMENT_PROPERTY);
            String licenseAgreementText = IOUtils
                    .toString(new ClassPathResource(licenseAgreementFileName).getInputStream());

            mav.addObject(LICENSE_AGREEMENT, licenseAgreementText);
        } catch (IOException e) {
            log.warn("Cannot load the License Agreement file", e);
        }
        return mav;
    }

    @RequestMapping(value = LICENSE_AGREEMENT_URL, method = RequestMethod.POST)
    public ModelAndView licenseAgreementPost(HttpServletRequest request) {
        ModelAndView mav = null;
        String accept = request.getParameter("accept");
        if (StringUtils.hasLength(accept) && accept.equals(Boolean.TRUE.toString())) {
            User user = this.sessionSecurityService.getCurrentUser();
            // Update current User with license agreement
            user = this.userService.acceptLicenseAgreement(user);
            // Refresh User authorities
            this.sessionSecurityService.refreshUserContext(request, user, null);
            mav = new ModelAndView(new RedirectView("/", true));
        } else {
            mav = this.licenseAgreementGet();
        }
        return mav;
    }
}