From 56beb174094725a944dfb1967890fa3ef83450eb Mon Sep 17 00:00:00 2001 From: egmp777 Date: Tue, 25 Nov 2014 16:52:51 -0500 Subject: [PATCH] Email Confirmation Article All Changes as of Video Nov 22 --- .../event/OnRegistrationComplete.java | 19 --- .../event/OnRegistrationCompleteEvent.java | 34 ++++ .../java/org/baeldung/event/Registration.java | 57 ------- .../event/listener/RegistrationListener.java | 44 +++++ .../event/service/RegistrationService.java | 50 ------ .../persistence/dao/UserRepository.java | 5 +- .../dao/VerificationTokenRepository.java | 5 +- .../org/baeldung/persistence/model/Role.java | 5 +- .../org/baeldung/persistence/model/User.java | 52 +++--- .../persistence/model/VerificationToken.java | 155 ++++++++---------- .../persistence/service/IUserService.java | 19 ++- .../baeldung/persistence/service/UserDto.java | 4 +- .../persistence/service/UserService.java | 117 +++++++------ ...SimpleUrlAuthenticationSuccessHandler.java | 2 +- .../security/MyUserDetailsService.java | 130 +++++++-------- .../java/org/baeldung/spring/AppConfig.java | 44 +++-- .../java/org/baeldung/spring/MvcConfig.java | 3 +- .../controller/RegistrationController.java | 145 ++++++++-------- .../src/main/resources/application.properties | 4 +- .../main/resources/messages_es_ES.properties | 4 +- .../src/main/webapp/WEB-INF/view/badUser.jsp | 3 +- .../src/main/webapp/WEB-INF/view/homepage.jsp | 3 + 22 files changed, 423 insertions(+), 481 deletions(-) delete mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationComplete.java create mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationCompleteEvent.java delete mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/event/Registration.java create mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/event/listener/RegistrationListener.java delete mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/event/service/RegistrationService.java diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationComplete.java b/spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationComplete.java deleted file mode 100644 index de77c4f53c..0000000000 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationComplete.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung.event; - -import org.springframework.context.ApplicationEvent; - -@SuppressWarnings("serial") -public class OnRegistrationComplete extends ApplicationEvent { - - public final Registration registration; - - public OnRegistrationComplete(Registration source) { - super(source); - this.registration=source; - } - - public Registration getRegistration() { - return registration; - } - -} diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationCompleteEvent.java b/spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationCompleteEvent.java new file mode 100644 index 0000000000..6dace5ad4a --- /dev/null +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/event/OnRegistrationCompleteEvent.java @@ -0,0 +1,34 @@ +package org.baeldung.event; + +import java.util.Locale; + +import org.baeldung.persistence.model.User; +import org.springframework.context.ApplicationEvent; + +@SuppressWarnings("serial") +public class OnRegistrationCompleteEvent extends ApplicationEvent { + + private final String appUrl; + private final Locale locale; + private final User user; + + public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) { + super(user); + this.user = user; + this.locale = locale; + this.appUrl = appUrl; + } + + public String getAppUrl() { + return appUrl; + } + + public Locale getLocale() { + return locale; + } + + public User getUser() { + return user; + } + +} diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/event/Registration.java b/spring-security-login-and-registration/src/main/java/org/baeldung/event/Registration.java deleted file mode 100644 index 1996d2f889..0000000000 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/event/Registration.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.baeldung.event; - -import java.util.Locale; -import org.baeldung.persistence.model.User; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.ApplicationEventPublisherAware; -import org.springframework.stereotype.Component; - -@Component -public class Registration implements ApplicationEventPublisherAware { - - private ApplicationEventPublisher eventPublisher; - - public String getAppUrl() { - return appUrl; - } - - public Locale getLocale() { - return locale; - } - - public void setAppUrl(String appUrl) { - this.appUrl = appUrl; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - public void setUser(User user) { - this.user = user; - } - - public User getUser() { - return user; - } - - private String appUrl; - private Locale locale; - private User user; - - public Registration() { - super(); - } - - public void deliver() { - this.eventPublisher.publishEvent(new OnRegistrationComplete(this)); - } - - @Override - public void setApplicationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { - this.eventPublisher = applicationEventPublisher; - - } - -} diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/event/listener/RegistrationListener.java b/spring-security-login-and-registration/src/main/java/org/baeldung/event/listener/RegistrationListener.java new file mode 100644 index 0000000000..7723c64121 --- /dev/null +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/event/listener/RegistrationListener.java @@ -0,0 +1,44 @@ +package org.baeldung.event.listener; + +import java.util.UUID; +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.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Component; + +@Component +public class RegistrationListener implements ApplicationListener { + @Autowired + private IUserService service; + + @Autowired + private MessageSource messages; + + @Autowired + private JavaMailSender mailSender; + + @Override + public void onApplicationEvent(OnRegistrationCompleteEvent event) { + this.confirmRegistration(event); + } + + private void confirmRegistration(OnRegistrationCompleteEvent event) { + User user = event.getUser(); + String token = UUID.randomUUID().toString(); + service.addVerificationToken(user, token); + String recipientAddress = user.getEmail(); + String subject = "Registration Confirmation"; + String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token; + String message = messages.getMessage("message.regSucc", null, event.getLocale()); + SimpleMailMessage email = new SimpleMailMessage(); + email.setTo(recipientAddress); + email.setSubject(subject); + email.setText(message + " \r\n" + "http://localhost:8080" + confirmationUrl); + mailSender.send(email); + } +} diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/event/service/RegistrationService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/event/service/RegistrationService.java deleted file mode 100644 index c555948400..0000000000 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/event/service/RegistrationService.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.baeldung.event.service; - - -import java.util.UUID; -import org.baeldung.event.OnRegistrationComplete; -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.SimpleMailMessage; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.stereotype.Service; - -@Service -public class RegistrationService implements - ApplicationListener { - @Autowired - private IUserService service; - @Autowired - private MessageSource messages; - - @Autowired - private JavaMailSender mailSender; - - @Override - public void onApplicationEvent(OnRegistrationComplete event) { - this.confirmRegistration(event); - } - - private void confirmRegistration(OnRegistrationComplete event) { - User user = event.getRegistration().getUser(); - String token = UUID.randomUUID().toString(); - service.addVerificationToken(user, token); - String recipientAddress = user.getEmail(); - String subject = "Registration Confirmation"; - String confirmationUrl = event.getRegistration().getAppUrl() - + "/regitrationConfirm.html?token=" + token; - String message = messages.getMessage("message.regSucc", null, event - .getRegistration().getLocale()); - SimpleMailMessage email = new SimpleMailMessage(); - email.setTo(recipientAddress); - email.setSubject(subject); - email.setText(message + " \r\n" + "http://localhost:8080" - + confirmationUrl); - mailSender.send(email); - - } - -} diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java index a7120b2e81..12f07d8692 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -4,7 +4,8 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.baeldung.persistence.model.User; public interface UserRepository extends JpaRepository { - public User findByEmail(String email); + public User findByEmail(String email); + + public void delete(User user); - public void delete(User user); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java index d51c79b36e..f9fc850d41 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/dao/VerificationTokenRepository.java @@ -1,9 +1,12 @@ package org.baeldung.persistence.dao; +import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.VerificationToken; import org.springframework.data.jpa.repository.JpaRepository; public interface VerificationTokenRepository extends JpaRepository { - public VerificationToken findByToken(String token); + public VerificationToken findByToken(String token); + + public VerificationToken findByUser(User user); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java index dcbdd8436b..2468fb997d 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java @@ -11,8 +11,8 @@ import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; -@Entity(name = "role") -@Table(name = "role") +@Entity +@Table public class Role { @Id @@ -28,7 +28,6 @@ public class Role { public Role() { super(); - } public Role(Integer role) { diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java index f947f4b7c0..2b5274f3eb 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java @@ -14,34 +14,28 @@ import javax.persistence.Table; @Table public class User { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - @Column(name = "firstName") - private String firstName; - @Column(name="lastName") + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "firstName") + private String firstName; + + @Column(name = "lastName") private String lastName; - @Column(name="email") + + @Column(name = "email") private String email; - @Column(name="password") + + @Column(name = "password") private String password; - - @OneToOne(mappedBy="user", - fetch = FetchType.EAGER, - cascade= CascadeType.ALL) - private VerificationToken verificationToken; - - @OneToOne(mappedBy = "user",fetch = FetchType.EAGER, cascade = CascadeType.ALL) + + @Column(name = "enabled") + private boolean enabled; + + @OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Role role; - public VerificationToken getVerificationToken() { - return verificationToken; - } - - public void setVerificationToken(VerificationToken verificationToken) { - this.verificationToken = verificationToken; - } - public Long getId() { return id; } @@ -90,6 +84,14 @@ public class User { this.role = role; } + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + @Override public int hashCode() { final int prime = 31; @@ -111,11 +113,11 @@ public class User { return false; return true; } + @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("User [firstName=").append(firstName).append("]"). - append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); + builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); return builder.toString(); } } \ No newline at end of file diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java index b73859e8a4..651df6c858 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/VerificationToken.java @@ -13,109 +13,94 @@ import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; -@Entity() -@Table() +@Entity +@Table public class VerificationToken { - private static final int EXPIRATION = 60 * 24; + private static final int EXPIRATION = 60 * 24; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; - @Column(name = "token") - private String token; + @Column(name = "token") + private String token; - @Column(name = "verified") - private boolean verified; + @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER) + @JoinColumn(name = "user_id") + private User user; - @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER) - @JoinColumn(name = "user_id") - private User user; + @Column(name = "expiry_date") + private Date expiryDate; - @Column(name = "expiry_date") - private Date expiryDate; + public VerificationToken() { + super(); + } - public VerificationToken() { - super(); + public VerificationToken(String token) { + super(); + this.token = token; + this.expiryDate = calculateExpiryDate(EXPIRATION); + } - } + public VerificationToken(String token, User user) { + super(); + this.token = token; + this.user = user; + this.expiryDate = calculateExpiryDate(EXPIRATION); + } - public VerificationToken(String token) { - super(); - this.token = token; - this.expiryDate = calculateExpiryDate(EXPIRATION); - } + public String getToken() { + return token; + } - public VerificationToken(String token, User user) { - super(); - this.token = token; - this.user = user; - this.expiryDate = calculateExpiryDate(EXPIRATION); - this.verified = false; - } + public void setToken(String token) { + this.token = token; + } - public String getToken() { - return token; - } + public User getUser() { + return user; + } - public void setToken(String token) { - this.token = token; - } + public void setUser(User user) { + this.user = user; + } - public boolean isVerified() { - return verified; - } + public Date getExpiryDate() { + return expiryDate; + } - public void setVerified(boolean verified) { - this.verified = verified; - } + public void setExpiryDate(Date expiryDate) { + this.expiryDate = expiryDate; + } - public User getUser() { - return user; - } + private Date calculateExpiryDate(int expiryTimeInMinutes) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Timestamp(cal.getTime().getTime())); + cal.add(Calendar.MINUTE, expiryTimeInMinutes); + return new Date(cal.getTime().getTime()); - public void setUser(User user) { - this.user = user; - } + } - public Date getExpiryDate() { - return expiryDate; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final VerificationToken verificationToken = (VerificationToken) obj; + if (!token.equals(verificationToken.getToken())) + return false; + return true; + } - public void setExpiryDate(Date expiryDate) { - this.expiryDate = expiryDate; - } - - private Date calculateExpiryDate(int expiryTimeInMinutes) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Timestamp(cal.getTime().getTime())); - cal.add(Calendar.MINUTE, expiryTimeInMinutes); - return new Date(cal.getTime().getTime()); - - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final VerificationToken verificationToken = (VerificationToken) obj; - if (!token.equals(verificationToken.getToken())) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Token [String=").append(token).append("]") - .append("[verified=").append(verified).append("]") - .append("[Expires").append(expiryDate).append("]"); - return builder.toString(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Token [String=").append(token).append("]").append("[Expires").append(expiryDate).append("]"); + return builder.toString(); + } } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java index 84e610561e..260dad9453 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/IUserService.java @@ -1,17 +1,24 @@ package org.baeldung.persistence.service; import org.baeldung.persistence.model.User; +import org.baeldung.persistence.model.VerificationToken; import org.baeldung.validation.service.EmailExistsException; public interface IUserService { public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; - public User getRegisteredUser(String email); - + /* public User getRegisteredUser(String email);*/ + public User getUser(String verificationToken); - - public void verifyRegisteredUser(User user); - - public void addVerificationToken(User user, String token); + + public void saveRegisteredUser(User user); + + public void addVerificationToken(User user, String token); + + public VerificationToken getVerificationToken(String VerificationToken); + + public void verifyUser(VerificationToken token); + + public void deleteUser(User user); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserDto.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserDto.java index f6c4040113..c8d63fb891 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserDto.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserDto.java @@ -24,8 +24,8 @@ public class UserDto { @NotNull @NotEmpty private String email; - - public String getEmail() { + + public String getEmail() { return email; } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java index c14f3ab6ba..ce292e43a5 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java @@ -13,63 +13,78 @@ import org.springframework.stereotype.Service; @Service public class UserService implements IUserService { - @Autowired - private UserRepository repository; - // NOV 6 - @Autowired - private VerificationTokenRepository tokenRepository; + @Autowired + private UserRepository repository; - @Transactional - @Override - public User registerNewUserAccount(UserDto accountDto) - throws EmailExistsException { - if (emailExist(accountDto.getEmail())) { - throw new EmailExistsException( - "There is an account with that email adress: " - + accountDto.getEmail()); - } - User user = new User(); - user.setFirstName(accountDto.getFirstName()); - user.setLastName(accountDto.getLastName()); - user.setPassword(accountDto.getPassword()); - user.setEmail(accountDto.getEmail()); - user.setRole(new Role(Integer.valueOf(1), user)); - return repository.save(user); - } + @Autowired + private VerificationTokenRepository tokenRepository; - private boolean emailExist(String email) { - User user = repository.findByEmail(email); - if (user != null) { - return true; - } - return false; - } + @Transactional + @Override + public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException { + if (emailExist(accountDto.getEmail())) { + throw new EmailExistsException("There is an account with that email adress: " + accountDto.getEmail()); + } + User user = new User(); + user.setFirstName(accountDto.getFirstName()); + user.setLastName(accountDto.getLastName()); + user.setPassword(accountDto.getPassword()); + user.setEmail(accountDto.getEmail()); + user.setRole(new Role(Integer.valueOf(1), user)); + return repository.save(user); + } - @Override - public User getRegisteredUser(String email) { + private boolean emailExist(String email) { + User user = repository.findByEmail(email); + if (user != null) { + return true; + } + return false; + } - User user = repository.findByEmail(email); - return user; + /* @Override + public User getRegisteredUser(String email) { - } + User user = repository.findByEmail(email); + return user; - @Override - public User getUser(String verificationToken) { - User user = tokenRepository.findByToken(verificationToken).getUser(); - return user; - } + }*/ - @Transactional - @Override - public void verifyRegisteredUser(User user) { - repository.save(user); - } + @Override + public User getUser(String verificationToken) { + User user = tokenRepository.findByToken(verificationToken).getUser(); + return user; + } - @Transactional - @Override - public void addVerificationToken(User user, String token) { - VerificationToken myToken = new VerificationToken(token, user); - user.setVerificationToken(myToken); - repository.save(user); - } + @Override + public VerificationToken getVerificationToken(String VerificationToken) { + return tokenRepository.findByToken(VerificationToken); + } + + @Transactional + @Override + public void saveRegisteredUser(User user) { + repository.save(user); + } + + @Transactional + @Override + public void verifyUser(VerificationToken token) { + tokenRepository.save(token); + } + + @Transactional + @Override + public void deleteUser(User user) { + repository.delete(user); + } + + @Transactional + @Override + public void addVerificationToken(User user, String token) { + VerificationToken myToken = new VerificationToken(token, user); + // user.setVerificationToken(myToken); + tokenRepository.save(myToken); + // repository.save(user); + } } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 825eaba71e..591b821ab2 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -55,7 +55,7 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu } } if (isUser) { - return "/homepage.html"; + return "/homepage.html?user="+authentication.getName(); } else if (isAdmin) { return "/console.html"; } else { diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java index 38a61ee342..836c522bd7 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -1,17 +1,17 @@ package org.baeldung.security; import java.util.ArrayList; -import java.util.Calendar; import java.util.Collection; import java.util.List; - import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.baeldung.persistence.dao.UserRepository; +import org.baeldung.persistence.dao.VerificationTokenRepository; import org.baeldung.persistence.model.User; +import org.baeldung.persistence.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.security.core.GrantedAuthority; @@ -23,83 +23,65 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public class MyUserDetailsService implements UserDetailsService { - private final Logger LOGGER = LoggerFactory.getLogger(getClass()); + private final Logger LOGGER = LoggerFactory.getLogger(getClass()); - // OCT 21 - // @Autowired - private UserRepository userRepository; - @Autowired - private MessageSource messages; + private UserRepository userRepository; + @Autowired + private IUserService service; + @Autowired + private MessageSource messages; + @Autowired + private VerificationTokenRepository tokenRepository;; - @Autowired - public MyUserDetailsService(UserRepository repository) { - this.userRepository = repository; - } + @Autowired + public MyUserDetailsService(UserRepository repository) { + this.userRepository = repository; + } - public UserDetails loadUserByUsername(String email) - throws UsernameNotFoundException { - boolean enabled = true; - boolean accountNonExpired = true; - boolean credentialsNonExpired = true; - boolean accountNonLocked = true; - try { - LOGGER.debug("Loading user by username: {}", email); - User user = userRepository.findByEmail(email); - // OCT 21 - Calendar cal = Calendar.getInstance(); - LOGGER.debug("Found user: {}", user); - if (user == null) { - return new org.springframework.security.core.userdetails.User( - " ", " ", enabled, true, true, true, - getAuthorities(new Integer(1))); - } - // OCT 21 - if (!(user.getVerificationToken().isVerified())) { - enabled = false; - } - // OCT 21 - if ((user.getVerificationToken().isVerified()) - && (user.getVerificationToken().getExpiryDate().getTime() - cal - .getTime().getTime()) <= 0) { - userRepository.delete(user); - // DEBUGGING - System.out.println("Deleted"); + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + boolean enabled = true; + boolean accountNonExpired = true; + boolean credentialsNonExpired = true; + boolean accountNonLocked = true; + try { + LOGGER.debug("Loading user by username: {}", email); + User user = userRepository.findByEmail(email); + LOGGER.debug("Found user: {}", user); + if (user == null) { + return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1))); + } + if (!user.isEnabled()) { + 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())); - accountNonExpired = false; - } - return new org.springframework.security.core.userdetails.User( - user.getEmail(), user.getPassword().toLowerCase(), enabled, - accountNonExpired, credentialsNonExpired, accountNonLocked, - getAuthorities(user.getRole().getRole())); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - } catch (Exception e) { - throw new RuntimeException(e); - } - } + private Collection getAuthorities(Integer role) { + List authList = getGrantedAuthorities(getRoles(role)); + return authList; + } - private Collection getAuthorities(Integer role) { - List authList = getGrantedAuthorities(getRoles(role)); - return authList; - } + public List getRoles(Integer role) { + List roles = new ArrayList(); + if (role.intValue() == 2) { + roles.add("ROLE_ADMIN"); + } else if (role.intValue() == 1) { + roles.add("ROLE_USER"); + } + return roles; + } - public List getRoles(Integer role) { - List roles = new ArrayList(); - - if (role.intValue() == 2) { - roles.add("ROLE_ADMIN"); - - } else if (role.intValue() == 1) { - roles.add("ROLE_USER"); - } - return roles; - } - - private static List getGrantedAuthorities( - List roles) { - List authorities = new ArrayList(); - for (String role : roles) { - authorities.add(new SimpleGrantedAuthority(role)); - } - return authorities; - } + private static List getGrantedAuthorities(List roles) { + List authorities = new ArrayList(); + for (String role : roles) { + authorities.add(new SimpleGrantedAuthority(role)); + } + return authorities; + } } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java index 8179317c3d..4708c53a14 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/AppConfig.java @@ -13,33 +13,31 @@ import org.springframework.core.env.Environment; import org.springframework.mail.javamail.JavaMailSenderImpl; @Configuration -@ComponentScan(basePackages = { "org.baeldung.event.service", - "org.baeldung.event", "org.baeldung.persistence.service", - "org.baeldung.persistence.dao" }) +@ComponentScan(basePackages = { "org.baeldung.event.service", "org.baeldung.event", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) @Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class }) @PropertySource("classpath:application.properties") public class AppConfig { - @Autowired - private Environment env; + @Autowired + private Environment env; - @Bean - public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } + @Bean + public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { + return new PropertySourcesPlaceholderConfigurer(); + } - @Bean - public JavaMailSenderImpl javaMailSenderImpl() { - JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl(); - mailSenderImpl.setHost(env.getProperty("smtp.host")); - mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class)); - mailSenderImpl.setProtocol(env.getProperty("smtp.protocol")); - mailSenderImpl.setUsername(env.getProperty("smtp.username")); - mailSenderImpl.setPassword(env.getProperty("smtp.password")); - Properties javaMailProps = new Properties(); - javaMailProps.put("mail.smtp.auth", true); - javaMailProps.put("mail.smtp.starttls.enable", true); - mailSenderImpl.setJavaMailProperties(javaMailProps); - return mailSenderImpl; - } + @Bean + public JavaMailSenderImpl javaMailSenderImpl() { + JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl(); + mailSenderImpl.setHost(env.getProperty("smtp.host")); + mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class)); + mailSenderImpl.setProtocol(env.getProperty("smtp.protocol")); + mailSenderImpl.setUsername(env.getProperty("smtp.username")); + mailSenderImpl.setPassword(env.getProperty("smtp.password")); + Properties javaMailProps = new Properties(); + javaMailProps.put("mail.smtp.auth", true); + javaMailProps.put("mail.smtp.starttls.enable", true); + mailSenderImpl.setJavaMailProperties(javaMailProps); + return mailSenderImpl; + } } \ No newline at end of file diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java index 364e63c3fb..35f799d770 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/MvcConfig.java @@ -22,8 +22,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration -@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", - "org.baeldung.persistence.dao" }) +@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) @EnableWebMvc public class MvcConfig extends WebMvcConfigurerAdapter { diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java b/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java index dd9e38a8de..407ca58f4a 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/web/controller/RegistrationController.java @@ -1,15 +1,17 @@ package org.baeldung.web.controller; +import java.util.Calendar; import javax.validation.Valid; -import org.baeldung.event.Registration; import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.VerificationToken; import org.baeldung.persistence.service.UserDto; import org.baeldung.persistence.service.IUserService; +import org.baeldung.event.OnRegistrationCompleteEvent; import org.baeldung.validation.service.EmailExistsException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.MessageSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Controller; @@ -26,84 +28,77 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class RegistrationController { - private final Logger LOGGER = LoggerFactory.getLogger(getClass()); - private IUserService service; - @Autowired - private MessageSource messages; - @Autowired - private JavaMailSender mailSender; - @Autowired - private Registration registration; + private final Logger LOGGER = LoggerFactory.getLogger(getClass()); + private IUserService service; + + @Autowired + private MessageSource messages; + + @Autowired + private JavaMailSender mailSender; + + @Autowired + private ApplicationEventPublisher eventPublisher; - @Autowired - public RegistrationController(IUserService service) { - this.service = service; - } + @Autowired + public RegistrationController(IUserService service) { + this.service = service; + } - @RequestMapping(value = "/user/registration", method = RequestMethod.GET) - public String showRegistrationForm(WebRequest request, Model model) { - LOGGER.debug("Rendering registration page."); - UserDto accountDto = new UserDto(); - model.addAttribute("user", accountDto); - return "registration"; - } + @RequestMapping(value = "/user/registration", method = RequestMethod.GET) + public String showRegistrationForm(WebRequest request, Model model) { + LOGGER.debug("Rendering registration page."); + UserDto accountDto = new UserDto(); + model.addAttribute("user", accountDto); + return "registration"; + } - @RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET) - public String confirmRegistration(WebRequest request, Model model, - @RequestParam("token") String token) { - User user = service.getUser(token); - if (user == null) { - model.addAttribute("message", messages.getMessage( - "auth.message.invalidUser", null, request.getLocale())); - return "redirect:/badUser.html?lang=" - + request.getLocale().getLanguage(); - } + @RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET) + public String confirmRegistration(WebRequest request, Model model, @RequestParam("token") String token) { + VerificationToken verificationToken = service.getVerificationToken(token); + if (verificationToken == null) { + model.addAttribute("message", messages.getMessage("auth.message.invalidToken", null, request.getLocale())); + return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage(); - VerificationToken verificationToken = user.getVerificationToken(); - if (!verificationToken.getToken().equals(token)) { - model.addAttribute("message", messages.getMessage( - "auth.message.invalidToken", null, request.getLocale())); - return "redirect:/badUser.html?lang=" - + request.getLocale().getLanguage(); - } - user.getVerificationToken().setVerified(true); - service.verifyRegisteredUser(user); - return "redirect:/login.html?lang=" + request.getLocale().getLanguage(); - } + } + User user = verificationToken.getUser(); + Calendar cal = Calendar.getInstance(); + if (user == null) { + model.addAttribute("message", messages.getMessage("auth.message.invalidUser", null, request.getLocale())); + return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage(); + } + if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) { + user.setEnabled(false); + } else { + user.setEnabled(true); + } + service.saveRegisteredUser(user); + return "redirect:/login.html?lang=" + request.getLocale().getLanguage(); + } - @RequestMapping(value = "/user/registration", method = RequestMethod.POST) - public ModelAndView registerUserAccount( - @ModelAttribute("user") @Valid UserDto accountDto, - BindingResult result, WebRequest request, Errors errors) { + @RequestMapping(value = "/user/registration", method = RequestMethod.POST) + public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, BindingResult result, WebRequest request, Errors errors) { + LOGGER.debug("Registering user account with information: {}", accountDto); + User registered = new User(); + String appUrl = request.getContextPath(); + if (result.hasErrors()) { + return new ModelAndView("registration", "user", accountDto); + } + registered = createUserAccount(accountDto); + if (registered == null) { + result.rejectValue("email", "message.regError"); + } + eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, request.getLocale(), appUrl)); + return new ModelAndView("successRegister", "user", accountDto); + } - LOGGER.debug("Registering user account with information: {}", - accountDto); - User registered = new User(); - String appUrl = request.getContextPath(); - if (!result.hasErrors()) - registered = createUserAccount(accountDto, result); - if (registered == null) { - result.rejectValue("email", "message.regError"); - } - if (result.hasErrors()) { - return new ModelAndView("registration", "user", accountDto); - } else { - registration.setAppUrl(appUrl); - registration.setLocale(request.getLocale()); - registration.setUser(registered); - registration.deliver(); - return new ModelAndView("successRegister", "user", accountDto); - } - } - - private User createUserAccount(UserDto accountDto, BindingResult result) { - User registered = null; - try { - registered = service.registerNewUserAccount(accountDto); - - } catch (EmailExistsException e) { - return null; - } - return registered; - } + private User createUserAccount(UserDto accountDto) { + User registered = null; + try { + registered = service.registerNewUserAccount(accountDto); + } catch (EmailExistsException e) { + return null; + } + return registered; + } } diff --git a/spring-security-login-and-registration/src/main/resources/application.properties b/spring-security-login-and-registration/src/main/resources/application.properties index 9dbeb6e4b4..44c39f583b 100644 --- a/spring-security-login-and-registration/src/main/resources/application.properties +++ b/spring-security-login-and-registration/src/main/resources/application.properties @@ -12,6 +12,6 @@ hibernate.hbm2ddl.auto=create-drop smtp.host=smtp.gmail.com smtp.port=465 smtp.protocol=smtps -smtp.username= +smtp.username=xxx@gmail.com smtp.password= -support.email= +support.email=xxx@gmail.com diff --git a/spring-security-login-and-registration/src/main/resources/messages_es_ES.properties b/spring-security-login-and-registration/src/main/resources/messages_es_ES.properties index 67ea26c78c..b7e77cac4d 100644 --- a/spring-security-login-and-registration/src/main/resources/messages_es_ES.properties +++ b/spring-security-login-and-registration/src/main/resources/messages_es_ES.properties @@ -34,8 +34,8 @@ label.pages.logout=Salir label.pages.admin=Administrador label.pages.home.title=Inicio label.pages.home.message=Bienveni@ a Casa -label.pages.admin.message=Bienvenido Admin -label.pages.user.message=Bienvenido Usuario +label.pages.admin.message=Bienvenid@ Admin +label.pages.user.message=Bienvenid@ Usuari@ label.successRegister.title=Registro Exitoso label.badUser.title=Enlace Invalido ValidEmail.user.email=Cuenta correo invlida! diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/badUser.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/badUser.jsp index 6acb83160a..348caac58a 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/badUser.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/badUser.jsp @@ -13,7 +13,8 @@ code="label.badUser.title">

- ${message} +
+ ${param.message}


">" rel="stylesheet"> +