org.encuestame.mvc.page.ForgetPasswordController.java Source code

Java tutorial

Introduction

Here is the source code for org.encuestame.mvc.page.ForgetPasswordController.java

Source

/*
 ************************************************************************************
 * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
 * encuestame Development Team.
 * Licensed under the Apache Software License version 2.0
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to  in writing,  software  distributed
 * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
 * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
 * specific language governing permissions and limitations under the License.
 ************************************************************************************
 */
package org.encuestame.mvc.page;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.encuestame.core.filter.RequestSessionMap;
import org.encuestame.core.util.ConvertDomainBean;
import org.encuestame.core.util.PasswordGenerator;
import org.encuestame.mvc.controller.security.AbstractSecurityController;
import org.encuestame.mvc.validator.ValidateOperations;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.util.exception.EnMeException;
import org.encuestame.util.exception.EnMeNoResultsFoundException;
import org.encuestame.utils.captcha.ReCaptchaResponse;
import org.encuestame.utils.security.ForgotPasswordBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * Forgot Password Controller.
 * @author Picado, Juan juanATencuestame.org
 * @since Jun 14, 2010 8:37:05 PM
 */
@Controller
@SessionAttributes(types = ForgotPasswordBean.class)
public class ForgetPasswordController extends AbstractSecurityController {

    /**
     * Log.
     */
    private Log log = LogFactory.getLog(this.getClass());

    /**
     *
     * @param model
     * @return
     */

    @RequestMapping(value = "/user/forgot", method = RequestMethod.GET)
    public String addHandler(ModelMap model) {
        log.info("/forgot");
        setCss(model, "user");
        final ForgotPasswordBean forgot = new ForgotPasswordBean();
        final String captcha = getReCaptcha().createRecaptchaHtml(null, null);
        forgot.setCaptcha(captcha);
        model.addAttribute(forgot);
        return "forgot";
    }

    /**
     * Process Submit.
     *
     * @param req
     * @param challenge
     * @param response
     * @param user
     * @param result
     * @param status
     * @return
     * @throws EnMeNoResultsFoundException
     */
    @RequestMapping(value = "/user/forgot", method = RequestMethod.POST)
    public String forgotSubmitForm(HttpServletRequest req, ModelMap model,
            @RequestParam(value = "recaptcha_challenge_field", required = false) String challenge,
            @RequestParam(value = "recaptcha_response_field", required = false) String response,
            @ModelAttribute ForgotPasswordBean user, BindingResult result, SessionStatus status)
            throws EnMeNoResultsFoundException {
        log.info("recaptcha_challenge_field " + challenge);
        log.info("recaptcha_response_field " + response);
        log.info("result erros  " + result.getAllErrors().size());
        log.info("result erros  " + result.getErrorCount());
        final String email = user.getEmail() == null ? "" : user.getEmail();
        setCss(model, "user");
        if (!email.isEmpty()) {
            log.debug("email " + email);
            final ReCaptchaResponse reCaptchaResponse = getReCaptcha().checkAnswer(req.getRemoteAddr(), challenge,
                    response);
            final ValidateOperations validation = new ValidateOperations(getSecurityService());
            boolean _isValidEmailFormat = validation.validateEmail(email);
            log.info("EMAIL FORMAT NOT VALID --> " + _isValidEmailFormat);
            if (_isValidEmailFormat) {
                final UserAccount userValidate = validation.checkifEmailExist(email);
                if (userValidate == null) {
                    result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, "");
                }
                log.info("reCaptchaResponse " + reCaptchaResponse.isValid());
                //validate reCaptcha
                validation.validateCaptcha(reCaptchaResponse, result);
                if (reCaptchaResponse.getErrorMessage() != null) {
                    RequestSessionMap.getCurrent(req).put("resetError", Boolean.TRUE);
                    RequestSessionMap.getCurrent(req).put("resetErrorMessage", reCaptchaResponse.getErrorMessage());
                    log.fatal("reCaptcha Fatal Error: " + reCaptchaResponse.getErrorMessage());
                }
                log.info("result.hasErrors() " + result.hasErrors());
                if (result.hasErrors()) {
                    return "forgot";
                } else {
                    final String password = PasswordGenerator.getPassword(6);
                    try {
                        /*
                         * Stuffs to change;
                         * 1. user should be to change own password, not auto generate
                         * 2. instead redirect to sign in page, should be to success page.
                         */
                        getSecurityService().renewPassword(
                                ConvertDomainBean.convertBasicSecondaryUserToUserBean(userValidate), password);
                    } catch (EnMeException e) {
                        log.error("Error Renewd password " + e.getMessage());
                        return "forgot";
                    }
                    status.setComplete();
                    log.info("password generated: " + password);
                    final ForgotPasswordBean forgot = new ForgotPasswordBean();
                    model.addAttribute("forgotPasswordBean", forgot);
                    return "/user/checkyouremail";
                }
            } else {
                log.info("EMAIL FORMAT NOT VALID");
                result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, "");
                return "forgot";
            }
        } else {
            result.rejectValue("email", "secure.email.emtpy", null, "");
            return "forgot";
        }
    }
}