modify registration api

This commit is contained in:
DOHA 2015-02-16 19:46:35 +02:00
parent d1eb4546bd
commit 628a293299
5 changed files with 86 additions and 72 deletions

View File

@ -14,14 +14,13 @@ import org.baeldung.persistence.service.IUserService;
import org.baeldung.persistence.service.UserDto; import org.baeldung.persistence.service.UserDto;
import org.baeldung.registration.OnRegistrationCompleteEvent; import org.baeldung.registration.OnRegistrationCompleteEvent;
import org.baeldung.validation.EmailExistsException; import org.baeldung.validation.EmailExistsException;
import org.baeldung.web.error.UserNotFoundException;
import org.baeldung.web.util.GenericResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -37,11 +36,11 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@Controller @Controller
public class Registration2Controller { @RequestMapping(value = "/old")
public class OldRegistrationController {
private final Logger LOGGER = LoggerFactory.getLogger(getClass()); private final Logger LOGGER = LoggerFactory.getLogger(getClass());
@Autowired @Autowired
@ -62,13 +61,13 @@ public class Registration2Controller {
@Autowired @Autowired
private Environment env; private Environment env;
public Registration2Controller() { public OldRegistrationController() {
} }
// API // API
@RequestMapping(value = "/user/registration2", method = RequestMethod.GET) @RequestMapping(value = "/user/registration", method = RequestMethod.GET)
public String showRegistrationForm(final HttpServletRequest request, final Model model) { public String showRegistrationForm(final HttpServletRequest request, final Model model) {
LOGGER.debug("Rendering registration page."); LOGGER.debug("Rendering registration page.");
final UserDto accountDto = new UserDto(); final UserDto accountDto = new UserDto();
@ -76,7 +75,7 @@ public class Registration2Controller {
return "registration"; return "registration";
} }
@RequestMapping(value = "/regitrationConfirm2", method = RequestMethod.GET) @RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
public String confirmRegistration(final HttpServletRequest request, final Model model, @RequestParam("token") final String token) { public String confirmRegistration(final HttpServletRequest request, final Model model, @RequestParam("token") final String token) {
final Locale locale = request.getLocale(); final Locale locale = request.getLocale();
@ -102,7 +101,7 @@ public class Registration2Controller {
return "redirect:/login.html?lang=" + locale.getLanguage(); return "redirect:/login.html?lang=" + locale.getLanguage();
} }
@RequestMapping(value = "/user/registration2", method = RequestMethod.POST) @RequestMapping(value = "/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid final UserDto accountDto, final BindingResult result, final HttpServletRequest request, final Errors errors) { public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid final UserDto accountDto, final BindingResult result, final HttpServletRequest request, final Errors errors) {
LOGGER.debug("Registering user account with information: {}", accountDto); LOGGER.debug("Registering user account with information: {}", accountDto);
if (result.hasErrors()) { if (result.hasErrors()) {
@ -124,34 +123,54 @@ public class Registration2Controller {
return new ModelAndView("successRegister", "user", accountDto); return new ModelAndView("successRegister", "user", accountDto);
} }
@RequestMapping(value = "/user/resendRegistrationToken2", method = RequestMethod.GET) @RequestMapping(value = "/user/resendRegistrationToken", method = RequestMethod.GET)
public @ResponseBody GenericResponse resendRegistrationToken2(final HttpServletRequest request, @RequestParam("token") final String existingToken) { public String resendRegistrationToken(final HttpServletRequest request, final Model model, @RequestParam("token") final String existingToken) {
final Locale locale = request.getLocale();
final VerificationToken newToken = userService.generateNewVerificationToken(existingToken); final VerificationToken newToken = userService.generateNewVerificationToken(existingToken);
final User user = userService.getUser(newToken.getToken()); final User user = userService.getUser(newToken.getToken());
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); try {
final SimpleMailMessage email = constructResetVerificationTokenEmail(appUrl, request.getLocale(), newToken, user); final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
mailSender.send(email); final SimpleMailMessage email = constructResetVerificationTokenEmail(appUrl, request.getLocale(), newToken, user);
return new GenericResponse(messages.getMessage("message.resendToken", null, request.getLocale())); mailSender.send(email);
} catch (final MailAuthenticationException e) {
LOGGER.debug("MailAuthenticationException", e);
return "redirect:/emailError.html?lang=" + locale.getLanguage();
} catch (final Exception e) {
LOGGER.debug(e.getLocalizedMessage(), e);
model.addAttribute("message", e.getLocalizedMessage());
return "redirect:/login.html?lang=" + locale.getLanguage();
}
model.addAttribute("message", messages.getMessage("message.resendToken", null, locale));
return "redirect:/login.html?lang=" + locale.getLanguage();
} }
@RequestMapping(value = "/user/resetPassword2", method = RequestMethod.POST) @RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST)
public @ResponseBody GenericResponse resetPassword2(final HttpServletRequest request, @RequestParam("email") final String userEmail) { public String resetPassword(final HttpServletRequest request, final Model model, @RequestParam("email") final String userEmail) {
final User user = userService.findUserByEmail(userEmail); final User user = userService.findUserByEmail(userEmail);
if (user == null) { if (user == null) {
throw new UserNotFoundException(); model.addAttribute("message", messages.getMessage("message.userNotFound", null, request.getLocale()));
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
} }
final String token = UUID.randomUUID().toString(); final String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token); userService.createPasswordResetTokenForUser(user, token);
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); try {
final SimpleMailMessage email = constructResetTokenEmail(appUrl, request.getLocale(), token, user); final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
mailSender.send(email); final SimpleMailMessage email = constructResetTokenEmail(appUrl, request.getLocale(), token, user);
mailSender.send(email);
return new GenericResponse(messages.getMessage("message.resetPasswordEmail", null, request.getLocale())); } catch (final MailAuthenticationException e) {
LOGGER.debug("MailAuthenticationException", e);
return "redirect:/emailError.html?lang=" + request.getLocale().getLanguage();
} catch (final Exception e) {
LOGGER.debug(e.getLocalizedMessage(), e);
model.addAttribute("message", e.getLocalizedMessage());
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
}
model.addAttribute("message", messages.getMessage("message.resetPasswordEmail", null, request.getLocale()));
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
} }
// ==== will not be changed this is used as the confirmation url of reset password token @RequestMapping(value = "/user/changePassword", method = RequestMethod.GET)
@RequestMapping(value = "/user/changePassword2", method = RequestMethod.GET)
public String changePassword(final HttpServletRequest request, final Model model, @RequestParam("id") final long id, @RequestParam("token") final String token) { public String changePassword(final HttpServletRequest request, final Model model, @RequestParam("id") final long id, @RequestParam("token") final String token) {
final Locale locale = request.getLocale(); final Locale locale = request.getLocale();
@ -175,18 +194,21 @@ public class Registration2Controller {
return "redirect:/updatePassword.html?lang=" + locale.getLanguage(); return "redirect:/updatePassword.html?lang=" + locale.getLanguage();
} }
@RequestMapping(value = "/user/savePassword2", method = RequestMethod.POST) @RequestMapping(value = "/user/savePassword", method = RequestMethod.POST)
@PreAuthorize("hasRole('READ_PRIVILEGE')") @PreAuthorize("hasRole('READ_PRIVILEGE')")
public @ResponseBody GenericResponse savePassword(final HttpServletRequest request, @RequestParam("password") final String password) { public String savePassword(final HttpServletRequest request, final Model model, @RequestParam("password") final String password) {
final Locale locale = request.getLocale();
final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
userService.changeUserPassword(user, password); userService.changeUserPassword(user, password);
return new GenericResponse(messages.getMessage("message.resetPasswordSuc", null, request.getLocale())); model.addAttribute("message", messages.getMessage("message.resetPasswordSuc", null, locale));
return "redirect:/login.html?lang=" + locale;
} }
// NON-API // NON-API
private final SimpleMailMessage constructResetVerificationTokenEmail(final String contextPath, final Locale locale, final VerificationToken newToken, final User user) { private final SimpleMailMessage constructResetVerificationTokenEmail(final String contextPath, final Locale locale, final VerificationToken newToken, final User user) {
final String confirmationUrl = contextPath + "/regitrationConfirm.html?token=" + newToken.getToken(); final String confirmationUrl = contextPath + "/old/regitrationConfirm.html?token=" + newToken.getToken();
final String message = messages.getMessage("message.resendToken", null, locale); final String message = messages.getMessage("message.resendToken", null, locale);
final SimpleMailMessage email = new SimpleMailMessage(); final SimpleMailMessage email = new SimpleMailMessage();
email.setSubject("Resend Registration Token"); email.setSubject("Resend Registration Token");
@ -197,7 +219,7 @@ public class Registration2Controller {
} }
private final SimpleMailMessage constructResetTokenEmail(final String contextPath, final Locale locale, final String token, final User user) { private final SimpleMailMessage constructResetTokenEmail(final String contextPath, final Locale locale, final String token, final User user) {
final String url = contextPath + "/user/changePassword2?id=" + user.getId() + "&token=" + token; final String url = contextPath + "/old/user/changePassword?id=" + user.getId() + "&token=" + token;
final String message = messages.getMessage("message.resetPassword", null, locale); final String message = messages.getMessage("message.resetPassword", null, locale);
final SimpleMailMessage email = new SimpleMailMessage(); final SimpleMailMessage email = new SimpleMailMessage();
email.setTo(user.getEmail()); email.setTo(user.getEmail());

View File

@ -14,13 +14,14 @@ import org.baeldung.persistence.service.IUserService;
import org.baeldung.persistence.service.UserDto; import org.baeldung.persistence.service.UserDto;
import org.baeldung.registration.OnRegistrationCompleteEvent; import org.baeldung.registration.OnRegistrationCompleteEvent;
import org.baeldung.validation.EmailExistsException; import org.baeldung.validation.EmailExistsException;
import org.baeldung.web.error.UserNotFoundException;
import org.baeldung.web.util.GenericResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -36,6 +37,7 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@Controller @Controller
@ -123,54 +125,38 @@ public class RegistrationController {
} }
@RequestMapping(value = "/user/resendRegistrationToken", method = RequestMethod.GET) @RequestMapping(value = "/user/resendRegistrationToken", method = RequestMethod.GET)
public String resendRegistrationToken(final HttpServletRequest request, final Model model, @RequestParam("token") final String existingToken) { @ResponseBody
final Locale locale = request.getLocale(); public GenericResponse resendRegistrationToken(final HttpServletRequest request, @RequestParam("token") final String existingToken) {
final VerificationToken newToken = userService.generateNewVerificationToken(existingToken); final VerificationToken newToken = userService.generateNewVerificationToken(existingToken);
final User user = userService.getUser(newToken.getToken()); final User user = userService.getUser(newToken.getToken());
try { final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); final SimpleMailMessage email = constructResetVerificationTokenEmail(appUrl, request.getLocale(), newToken, user);
final SimpleMailMessage email = constructResetVerificationTokenEmail(appUrl, request.getLocale(), newToken, user); mailSender.send(email);
mailSender.send(email);
} catch (final MailAuthenticationException e) { return new GenericResponse(messages.getMessage("message.resendToken", null, request.getLocale()));
LOGGER.debug("MailAuthenticationException", e);
return "redirect:/emailError.html?lang=" + locale.getLanguage();
} catch (final Exception e) {
LOGGER.debug(e.getLocalizedMessage(), e);
model.addAttribute("message", e.getLocalizedMessage());
return "redirect:/login.html?lang=" + locale.getLanguage();
}
model.addAttribute("message", messages.getMessage("message.resendToken", null, locale));
return "redirect:/login.html?lang=" + locale.getLanguage();
} }
// Reset password
@RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST) @RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST)
public String resetPassword(final HttpServletRequest request, final Model model, @RequestParam("email") final String userEmail) { @ResponseBody
public GenericResponse resetPassword(final HttpServletRequest request, @RequestParam("email") final String userEmail) {
final User user = userService.findUserByEmail(userEmail); final User user = userService.findUserByEmail(userEmail);
if (user == null) { if (user == null) {
model.addAttribute("message", messages.getMessage("message.userNotFound", null, request.getLocale())); throw new UserNotFoundException();
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
} }
final String token = UUID.randomUUID().toString(); final String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token); userService.createPasswordResetTokenForUser(user, token);
try { final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
final String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); final SimpleMailMessage email = constructResetTokenEmail(appUrl, request.getLocale(), token, user);
final SimpleMailMessage email = constructResetTokenEmail(appUrl, request.getLocale(), token, user); mailSender.send(email);
mailSender.send(email);
} catch (final MailAuthenticationException e) { return new GenericResponse(messages.getMessage("message.resetPasswordEmail", null, request.getLocale()));
LOGGER.debug("MailAuthenticationException", e);
return "redirect:/emailError.html?lang=" + request.getLocale().getLanguage();
} catch (final Exception e) {
LOGGER.debug(e.getLocalizedMessage(), e);
model.addAttribute("message", e.getLocalizedMessage());
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
}
model.addAttribute("message", messages.getMessage("message.resetPasswordEmail", null, request.getLocale()));
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
} }
@RequestMapping(value = "/user/changePassword", method = RequestMethod.GET) @RequestMapping(value = "/user/changePassword", method = RequestMethod.GET)
public String changePassword(final HttpServletRequest request, final Model model, @RequestParam("id") final long id, @RequestParam("token") final String token) { public String showChangePasswordPage(final HttpServletRequest request, final Model model, @RequestParam("id") final long id, @RequestParam("token") final String token) {
final Locale locale = request.getLocale(); final Locale locale = request.getLocale();
final PasswordResetToken passToken = userService.getPasswordResetToken(token); final PasswordResetToken passToken = userService.getPasswordResetToken(token);
@ -195,13 +181,11 @@ public class RegistrationController {
@RequestMapping(value = "/user/savePassword", method = RequestMethod.POST) @RequestMapping(value = "/user/savePassword", method = RequestMethod.POST)
@PreAuthorize("hasRole('READ_PRIVILEGE')") @PreAuthorize("hasRole('READ_PRIVILEGE')")
public String savePassword(final HttpServletRequest request, final Model model, @RequestParam("password") final String password) { @ResponseBody
final Locale locale = request.getLocale(); public GenericResponse savePassword(final HttpServletRequest request, @RequestParam("password") final String password) {
final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
userService.changeUserPassword(user, password); userService.changeUserPassword(user, password);
model.addAttribute("message", messages.getMessage("message.resetPasswordSuc", null, locale)); return new GenericResponse(messages.getMessage("message.resetPasswordSuc", null, request.getLocale()));
return "redirect:/login.html?lang=" + locale;
} }
// NON-API // NON-API

View File

@ -31,7 +31,7 @@ code="label.form.loginSignUp"></spring:message></a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
function resendToken(){ function resendToken(){
$.get("<c:url value="/user/resendRegistrationToken2"><c:param name="token" value="${param.token}"/></c:url>", function(data){ $.get("<c:url value="/user/resendRegistrationToken"><c:param name="token" value="${param.token}"/></c:url>", function(data){
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.message; window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.message;
}) })
.fail(function(data) { .fail(function(data) {
@ -44,6 +44,10 @@ function resendToken(){
} }
}); });
} }
$(document).ajaxStart(function() {
$("title").html("LOADING ...");
});
</script> </script>
</c:if> </c:if>
</body> </body>

View File

@ -43,7 +43,7 @@
<script type="text/javascript"> <script type="text/javascript">
function resetPass(){ function resetPass(){
var email = $("#email").val(); var email = $("#email").val();
$.post("<c:url value="/user/resetPassword2"></c:url>",{email: email} ,function(data){ $.post("<c:url value="/user/resetPassword"></c:url>",{email: email} ,function(data){
window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.message; window.location.href = "<c:url value="/login.html"></c:url>" + "?message=" + data.message;
}) })
.fail(function(data) { .fail(function(data) {
@ -56,6 +56,10 @@ function resetPass(){
} }
}); });
} }
$(document).ajaxStart(function() {
$("title").html("LOADING ...");
});
</script> </script>
</body> </body>

View File

@ -51,7 +51,7 @@ function savePass(){
$("#error").show(); $("#error").show();
return; return;
} }
$.post("<c:url value="/user/savePassword2"></c:url>",{password: pass} ,function(data){ $.post("<c:url value="/user/savePassword"></c:url>",{password: pass} ,function(data){
window.location.href = "<c:url value="/login.html"></c:url>" + "?message="+data.message; window.location.href = "<c:url value="/login.html"></c:url>" + "?message="+data.message;
}) })
.fail(function(data) { .fail(function(data) {