Email Confirmation Article

All Changes as of Video Nov 22
This commit is contained in:
egmp777 2014-11-25 16:52:51 -05:00
parent 65d7986485
commit 56beb17409
22 changed files with 423 additions and 481 deletions

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<OnRegistrationCompleteEvent> {
@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);
}
}

View File

@ -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<OnRegistrationComplete> {
@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);
}
}

View File

@ -4,7 +4,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.baeldung.persistence.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
public User findByEmail(String email);
public void delete(User user);
public void delete(User user);
}

View File

@ -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<VerificationToken, Long> {
public VerificationToken findByToken(String token);
public VerificationToken findByToken(String token);
public VerificationToken findByUser(User user);
}

View File

@ -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) {

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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);
}

View File

@ -24,8 +24,8 @@ public class UserDto {
@NotNull
@NotEmpty
private String email;
public String getEmail() {
public String getEmail() {
return email;
}

View File

@ -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);
}
}

View File

@ -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 {

View File

@ -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<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
private Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 2) {
roles.add("ROLE_ADMIN");
} else if (role.intValue() == 1) {
roles.add("ROLE_USER");
}
return roles;
}
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 2) {
roles.add("ROLE_ADMIN");
} else if (role.intValue() == 1) {
roles.add("ROLE_USER");
}
return roles;
}
private static List<GrantedAuthority> getGrantedAuthorities(
List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
private static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}

View File

@ -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;
}
}

View File

@ -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 {

View File

@ -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;
}
}

View File

@ -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

View File

@ -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!

View File

@ -13,7 +13,8 @@ code="label.badUser.title"></spring:message></title>
</head>
<body>
<h1>
${message}
<div class="alert alert-error">
${param.message}
</h1>
<br>
<a href="<c:url value="/user/registration" />"><spring:message

View File

@ -8,7 +8,9 @@
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="span12">
<sec:authorize access="hasRole('ROLE_USER')">
<spring:message code="label.pages.user.message"></spring:message>
@ -19,6 +21,7 @@
<spring:message code="label.pages.admin.message"></spring:message>
<br />
</sec:authorize>
${param.user}
<a href="<c:url value="/j_spring_security_logout" />"><spring:message
code="label.pages.logout"></spring:message></a> <a
href="<c:url value="/home.html" />"><spring:message