Merge pull request #86 from egmp777/master

Email Confirmation
This commit is contained in:
Eugen 2014-11-29 00:58:28 +02:00
commit 96129b8d89
19 changed files with 79 additions and 34 deletions

View File

@ -3,7 +3,9 @@ package org.baeldung.event;
import java.util.Locale;
import org.baeldung.persistence.model.User;
import org.baeldung.web.controller.RegistrationController;
import org.springframework.context.ApplicationEvent;
import org.springframework.web.context.request.WebRequest;
@SuppressWarnings("serial")
public class OnRegistrationCompleteEvent extends ApplicationEvent {
@ -30,5 +32,4 @@ public class OnRegistrationCompleteEvent extends ApplicationEvent {
public User getUser() {
return user;
}
}

View File

@ -1,12 +1,16 @@
package org.baeldung.event.listener;
import java.util.UUID;
import javax.mail.AuthenticationFailedException;
import org.baeldung.event.OnRegistrationCompleteEvent;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

View File

@ -32,10 +32,18 @@ public class User {
@Column(name = "enabled")
private boolean enabled;
@Column(name = "token_expired")
private boolean tokenExpired;
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Role role;
public User() {
super();
this.enabled = false;
this.tokenExpired = false;
}
public Long getId() {
return id;
}
@ -91,6 +99,15 @@ public class User {
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isTokenExpired() {
return tokenExpired;
}
public void setTokenExpired(boolean expired) {
this.tokenExpired = expired;
}
@Override
public int hashCode() {

View File

@ -27,7 +27,7 @@ public class VerificationToken {
private String token;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
@JoinColumn(nullable = false, name = "user_id")
private User user;
@Column(name = "expiry_date")

View File

@ -24,15 +24,15 @@ public class MyUserDetailsService implements UserDetailsService {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
@Autowired
private UserRepository userRepository;
@Autowired
private IUserService service;
@Autowired
private MessageSource messages;
@Autowired
public MyUserDetailsService(UserRepository repository) {
this.userRepository = repository;
public MyUserDetailsService() {
}
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
@ -48,8 +48,11 @@ public class MyUserDetailsService implements UserDetailsService {
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
}
if (!user.isEnabled()) {
enabled = false;
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
}
if (user.isTokenExpired()) {
accountNonExpired = false;
service.deleteUser(user);
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, accountNonExpired, true, true, getAuthorities(new Integer(1)));
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));

View File

@ -41,6 +41,7 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
registry.addViewController("/expiredAccount.html");
registry.addViewController("/regitrationConfirm.html");
registry.addViewController("/badUser.html");
registry.addViewController("/emailError.html");
registry.addViewController("/home.html");
registry.addViewController("/invalidSession.html");
registry.addViewController("/console.html");

View File

@ -29,6 +29,8 @@ import org.springframework.web.servlet.ModelAndView;
public class RegistrationController {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
@Autowired
private IUserService service;
@Autowired
@ -40,9 +42,8 @@ public class RegistrationController {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
public RegistrationController(IUserService service) {
this.service = service;
public RegistrationController() {
}
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
@ -59,7 +60,6 @@ public class RegistrationController {
if (verificationToken == null) {
model.addAttribute("message", messages.getMessage("auth.message.invalidToken", null, request.getLocale()));
return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage();
}
User user = verificationToken.getUser();
Calendar cal = Calendar.getInstance();
@ -68,10 +68,9 @@ public class RegistrationController {
return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage();
}
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
user.setEnabled(false);
} else {
user.setEnabled(true);
user.setTokenExpired(true);
}
user.setEnabled(true);
service.saveRegisteredUser(user);
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
}
@ -88,7 +87,11 @@ public class RegistrationController {
if (registered == null) {
result.rejectValue("email", "message.regError");
}
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
try {
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl));
} catch (Exception me) {
return new ModelAndView("emailError", "user", accountDto);
}
return new ModelAndView("successRegister", "user", accountDto);
}

View File

@ -8,11 +8,10 @@ init-db=false
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
################### JavaMail Configuration ##########################
smtp.host=smtp.gmail.com
smtp.port=465
smtp.protocol=smtps
smtp.username=xxx777@gmail.com
smtp.username=xxx@gmail.com
smtp.password=
support.email=xxx777@gmail.com
support.email=xxx@gmail.com

View File

@ -10,11 +10,12 @@ message.regError=An account for that username/email already exists. Please enter
message.lastName=Last name is required
message.firstName=First name required
message.badEmail=Invalid email address
message.email.config.error=Error in java mail configuration
token.message=Your token is:
auth.message.disabled=Your account is disabled please check your mail an click on the link to login.
auth.message.disabled=Your account is disabled please check your mail and click on the confirmation link
auth.message.expired=Your registration token has expired. Please register again.
auth.message.invalidUser=This username is invalid, or does not exist.
auth.message.invalidToken=Invalid account confirmation token. The confirmation link is not valid.
auth.message.invalidToken=Invalid account confirmation token.
label.user.email=Email:
label.user.firstName=First name:
label.user.lastName=Last name:

View File

@ -10,11 +10,12 @@ message.regError=Ya existe una cuenta con ese nombre de usuario. Ingrese un nomb
message.lastName=Por favor ingrese su apellido
message.firstName=Por favor ingrese su nombre
message.badEmail=Direccion de correo no es valida
message.email.config.error=Error en configuracion de java mail
token.message=Su token es:
auth.message.disabled=Su cuenta no esta habilitada. Hemos enviado a su correo un link para habilitar su cuenta.
auth.message.expired=Su ficha de registro ha caducado, por favor registrese de nuevo.
auth.message.invalidUser=Este nombre de usuario es invalido o no existe.
auth.message.invalidToken=Codigo de confirmacion incorrecto.El enlace de confirmacion no es valido.
auth.message.invalidToken=Codigo de confirmacion incorrecto.
label.user.email=Correo Electronico:
label.user.firstName=Nombre:
label.user.lastName=Apellido:

View File

@ -15,6 +15,8 @@
<intercept-url pattern="/expiredAccount*" access="permitAll" />
<intercept-url pattern="/registration*" access="permitAll" />
<intercept-url pattern="/badUser*" access="permitAll" />
<intercept-url pattern="/emailError*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/invalidSession*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()" />

View File

@ -6,6 +6,7 @@
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<div class="container">

View File

@ -0,0 +1,19 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<div class="container">
<div class="span12">
<h1 class="alert alert-error">
<spring:message code="message.email.config.error"></spring:message>
</h1>
</div>
</div>
</body>
</html>

View File

@ -9,7 +9,7 @@
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title>Expired</title>
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<h1>

View File

@ -6,6 +6,7 @@
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>

View File

@ -33,15 +33,7 @@
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<!-- <c:if test="${param.error != null}">
<div class="container">
<div class="span12">
<div class="alert alert-error">
<spring:message code="message.badCredentials"></spring:message>
</div>
</div>
</div>
</c:if> -->
<title><spring:message code="label.pages.home.title"></spring:message></title>
<script type="text/javascript">
function validate() {
if (document.f.j_username.value == ""

View File

@ -12,7 +12,7 @@
</div>
</c:if>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Logged Out</title>
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>

View File

@ -12,7 +12,7 @@
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Registration Success</title>
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>

View File

@ -11,7 +11,7 @@
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Registration Success</title>
<title><spring:message code="label.pages.home.title"></spring:message></title>
</head>
<body>
<div class="container">