Merge remote-tracking branch 'upstream/master'

This commit is contained in:
DOHA 2014-11-14 21:11:40 +02:00
commit 111a7ab69d
13 changed files with 262 additions and 160 deletions

View File

@ -28,5 +28,7 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="output" path="target/classes"/> <classpathentry kind="output" path="target/classes"/>
</classpath> </classpath>

View File

@ -0,0 +1,19 @@
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,57 @@
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,50 @@
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

@ -2,12 +2,9 @@ package org.baeldung.persistence.dao;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken;
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email); public User findByEmail(String email);
//NOV 5th
// public User findByVerificationToken(VerificationToken token); public void delete(User user);
//OCT 21
public void delete(User user);
} }

View File

@ -13,12 +13,12 @@ import javax.persistence.Table;
@Entity @Entity
@Table @Table
public class User { public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@Column(name="firstName") @Column(name = "firstName")
private String firstName; private String firstName;
@Column(name="lastName") @Column(name="lastName")
private String lastName; private String lastName;
@Column(name="email") @Column(name="email")
@ -26,7 +26,6 @@ public class User {
@Column(name="password") @Column(name="password")
private String password; private String password;
//EMAIL CONF ARTICLE
@OneToOne(mappedBy="user", @OneToOne(mappedBy="user",
fetch = FetchType.EAGER, fetch = FetchType.EAGER,
cascade= CascadeType.ALL) cascade= CascadeType.ALL)

View File

@ -1,7 +1,6 @@
package org.baeldung.persistence.model; package org.baeldung.persistence.model;
import java.util.Calendar; import java.util.Calendar;
import java.io.Serializable;
import java.sql.Date; import java.sql.Date;
import java.sql.Timestamp; import java.sql.Timestamp;
import javax.persistence.Column; import javax.persistence.Column;
@ -14,13 +13,11 @@ import javax.persistence.JoinColumn;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table; import javax.persistence.Table;
@Entity(/*name = "verrification_token"*/) @Entity()
@Table(/*name = "verrification_token"*/) @Table()
public class VerificationToken /*implements Serializable*/ { public class VerificationToken {
//private static final long serialVersionUID = 1L; private static final int EXPIRATION = 60 * 24;
private static final int EXPIRATION = 60 * 24/* 1 */;
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)

View File

@ -1,15 +1,17 @@
package org.baeldung.persistence.service; package org.baeldung.persistence.service;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken;
import org.baeldung.validation.service.EmailExistsException; import org.baeldung.validation.service.EmailExistsException;
public interface IUserService { public interface IUserService {
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException;
//OCT 21 EMAIL VERIFICATION
public User getRegisteredUser(String email); public User getRegisteredUser(String email);
public User getUser(String verificationToken);
public void verifyRegisteredUser(User user); public void verifyRegisteredUser(User user);
public void addVerificationToken(User user, String token);
} }

View File

@ -24,16 +24,7 @@ public class UserDto {
@NotNull @NotNull
@NotEmpty @NotEmpty
private String email; private String email;
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getEmail() { public String getEmail() {
return email; return email;
} }

View File

@ -3,6 +3,7 @@ package org.baeldung.persistence.service;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.dao.VerificationTokenRepository;
import org.baeldung.persistence.model.Role; import org.baeldung.persistence.model.Role;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken; import org.baeldung.persistence.model.VerificationToken;
@ -12,49 +13,63 @@ import org.springframework.stereotype.Service;
@Service @Service
public class UserService implements IUserService { public class UserService implements IUserService {
@Autowired @Autowired
private UserRepository repository; private UserRepository repository;
// NOV 6
@Autowired
private VerificationTokenRepository tokenRepository;
@Transactional @Transactional
@Override @Override
public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException { public User registerNewUserAccount(UserDto accountDto)
if (emailExist(accountDto.getEmail())) { throws EmailExistsException {
throw new EmailExistsException("There is an account with that email adress: " + accountDto.getEmail()); if (emailExist(accountDto.getEmail())) {
} throw new EmailExistsException(
User user = new User(); "There is an account with that email adress: "
user.setFirstName(accountDto.getFirstName()); + accountDto.getEmail());
user.setLastName(accountDto.getLastName()); }
user.setPassword(accountDto.getPassword()); User user = new User();
user.setEmail(accountDto.getEmail()); user.setFirstName(accountDto.getFirstName());
// ROLE WILL ALWAYS BE USER. HARDCODING IT user.setLastName(accountDto.getLastName());
user.setRole(new Role(Integer.valueOf(1), user)); user.setPassword(accountDto.getPassword());
//OCT 21 EMAIL VERIFICATION VERSION user.setEmail(accountDto.getEmail());
//MIGHT CHANGE HERE user.setRole(new Role(Integer.valueOf(1), user));
VerificationToken myToken = new VerificationToken(accountDto.getToken(),user); return repository.save(user);
user.setVerificationToken(myToken); }
return repository.save(user);
}
private boolean emailExist(String email) { private boolean emailExist(String email) {
User user = repository.findByEmail(email); User user = repository.findByEmail(email);
if (user != null) { if (user != null) {
return true; return true;
} }
return false; return false;
} }
//OCT 21 EMAIL VERIFICATION @Override
@Override public User getRegisteredUser(String email) {
public User getRegisteredUser(String email){
User user = repository.findByEmail(email);
User user = repository.findByEmail(email); return user;
return user;
}
}
@Override
@Transactional public User getUser(String verificationToken) {
@Override User user = tokenRepository.findByToken(verificationToken).getUser();
public void verifyRegisteredUser(User user){ return user;
repository.save(user); }
}
@Transactional
@Override
public void verifyRegisteredUser(User user) {
repository.save(user);
}
@Transactional
@Override
public void addVerificationToken(User user, String token) {
VerificationToken myToken = new VerificationToken(token, user);
user.setVerificationToken(myToken);
repository.save(user);
}
} }

View File

@ -13,31 +13,33 @@ import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.JavaMailSenderImpl;
@Configuration @Configuration
@ComponentScan(basePackages = { "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 }) @Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
@PropertySource("classpath:application.properties") @PropertySource("classpath:application.properties")
public class AppConfig { public class AppConfig {
@Autowired @Autowired
private Environment env; private Environment env;
@Bean @Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer(); return new PropertySourcesPlaceholderConfigurer();
} }
//OCT 21 @Bean
@Bean public JavaMailSenderImpl javaMailSenderImpl() {
public JavaMailSenderImpl javaMailSenderImpl() { JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl(); mailSenderImpl.setHost(env.getProperty("smtp.host"));
mailSenderImpl.setHost(env.getProperty("smtp.host")); mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class)); mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
mailSenderImpl.setProtocol(env.getProperty("smtp.protocol")); mailSenderImpl.setUsername(env.getProperty("smtp.username"));
mailSenderImpl.setUsername(env.getProperty("smtp.username")); mailSenderImpl.setPassword(env.getProperty("smtp.password"));
mailSenderImpl.setPassword(env.getProperty("smtp.password")); Properties javaMailProps = new Properties();
Properties javaMailProps = new Properties(); javaMailProps.put("mail.smtp.auth", true);
javaMailProps.put("mail.smtp.auth", true); javaMailProps.put("mail.smtp.starttls.enable", true);
javaMailProps.put("mail.smtp.starttls.enable", true); mailSenderImpl.setJavaMailProperties(javaMailProps);
mailSenderImpl.setJavaMailProperties(javaMailProps); return mailSenderImpl;
return mailSenderImpl; }
}
} }

View File

@ -1,10 +1,7 @@
package org.baeldung.web.controller; package org.baeldung.web.controller;
import java.util.Locale;
import java.util.UUID;
import javax.validation.Valid; import javax.validation.Valid;
import org.baeldung.event.Registration;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken; import org.baeldung.persistence.model.VerificationToken;
import org.baeldung.persistence.service.UserDto; import org.baeldung.persistence.service.UserDto;
@ -14,7 +11,6 @@ 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.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
@ -33,11 +29,11 @@ public class RegistrationController {
private final Logger LOGGER = LoggerFactory.getLogger(getClass()); private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private IUserService service; private IUserService service;
@Autowired @Autowired
// OCT 21
private MessageSource messages; private MessageSource messages;
// OCT 21
@Autowired @Autowired
private JavaMailSender mailSender; private JavaMailSender mailSender;
@Autowired
private Registration registration;
@Autowired @Autowired
public RegistrationController(IUserService service) { public RegistrationController(IUserService service) {
@ -47,52 +43,43 @@ public class RegistrationController {
@RequestMapping(value = "/user/registration", method = RequestMethod.GET) @RequestMapping(value = "/user/registration", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) { public String showRegistrationForm(WebRequest request, Model model) {
LOGGER.debug("Rendering registration page."); LOGGER.debug("Rendering registration page.");
//Changed name to accountDto
UserDto accountDto = new UserDto(); UserDto accountDto = new UserDto();
model.addAttribute("user", accountDto); model.addAttribute("user", accountDto);
return "registration"; return "registration";
} }
// OCT 21
// FOR EMAIL ARTICLE
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET) @RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
public String confirmRegistration(WebRequest request, Model model, public String confirmRegistration(WebRequest request, Model model,
@RequestParam("token") String token, @RequestParam("token") String token) {
@RequestParam("email") String email) { User user = service.getUser(token);
System.out.println(token); if (user == null) {
System.out.println(email); model.addAttribute("message", messages.getMessage(
//NOV 5 get user by token "auth.message.invalidUser", null, request.getLocale()));
User user = service.getRegisteredUser(email); return "redirect:/badUser.html?lang="
+ request.getLocale().getLanguage();
if(user==null) {
model.addAttribute("message",messages.getMessage("auth.message.invalidUser", null, request.getLocale()));
//return "badUser";
return "redirect:/badUser.html?lang="+request.getLocale().getLanguage();
} }
VerificationToken verificationToken = user.getVerificationToken(); VerificationToken verificationToken = user.getVerificationToken();
if(!verificationToken.getToken().equals(token)) { if (!verificationToken.getToken().equals(token)) {
model.addAttribute("message",messages.getMessage("auth.message.invalidToken", null, request.getLocale())); model.addAttribute("message", messages.getMessage(
//return "badUser"; "auth.message.invalidToken", null, request.getLocale()));
return "redirect:/badUser.html?lang="+request.getLocale().getLanguage(); return "redirect:/badUser.html?lang="
+ request.getLocale().getLanguage();
} }
user.getVerificationToken().setVerified(true); user.getVerificationToken().setVerified(true);
service.verifyRegisteredUser(user); service.verifyRegisteredUser(user);
//return "login"; return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
return "redirect:/login.html?lang="+request.getLocale().getLanguage();
} }
@RequestMapping(value = "/user/registration", method = RequestMethod.POST) @RequestMapping(value = "/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount( public ModelAndView registerUserAccount(
@ModelAttribute("user") @Valid UserDto accountDto, @ModelAttribute("user") @Valid UserDto accountDto,
BindingResult result, WebRequest request, Errors errors) { BindingResult result, WebRequest request, Errors errors) {
//OCT 21
LOGGER.debug("Registering user account with information: {}", accountDto); LOGGER.debug("Registering user account with information: {}",
accountDto);
User registered = new User(); User registered = new User();
//OCT 21 String appUrl = request.getContextPath();
String token = UUID.randomUUID().toString();
accountDto.setToken(token);
String appUrl = request.getContextPath();
if (!result.hasErrors()) if (!result.hasErrors())
registered = createUserAccount(accountDto, result); registered = createUserAccount(accountDto, result);
if (registered == null) { if (registered == null) {
@ -101,10 +88,10 @@ public class RegistrationController {
if (result.hasErrors()) { if (result.hasErrors()) {
return new ModelAndView("registration", "user", accountDto); return new ModelAndView("registration", "user", accountDto);
} else { } else {
//OCT 21 registration.setAppUrl(appUrl);
//FOR ARTICLE 2 registration.setLocale(request.getLocale());
//System.out.println("Will be Sending mail"); registration.setUser(registered);
sendConfirmMail(accountDto.getEmail(), request.getLocale(), accountDto.getToken(), appUrl); registration.deliver();
return new ModelAndView("successRegister", "user", accountDto); return new ModelAndView("successRegister", "user", accountDto);
} }
} }
@ -113,26 +100,10 @@ public class RegistrationController {
User registered = null; User registered = null;
try { try {
registered = service.registerNewUserAccount(accountDto); registered = service.registerNewUserAccount(accountDto);
} catch (EmailExistsException e) { } catch (EmailExistsException e) {
return null; return null;
} }
return registered; return registered;
} }
//OCT 21
//FOR ARTICLE 2
private void sendConfirmMail(String address, Locale locale, String token, String appUrl){
String recipientAddress = address;
String subject = "Registration Confirmation";
String confirmationUrl = appUrl + "/regitrationConfirm.html?token="+token+"&email="+address;
String message = messages.getMessage("message.regSucc", null, locale);
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,17 +1,17 @@
################### DataSource Configuration ########################## ################### DataSource Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/AUTHDATA jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_02?createDatabaseIfNotExist=true
jdbc.user=root jdbc.user=tutorialuser
###jdbc.pass=admin### jdbc.pass=tutorialmy5ql
init-db=false init-db=false
################### Hibernate Configuration ########################## ################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true hibernate.show_sql=false
hibernate.hbm2ddl.auto=validate hibernate.hbm2ddl.auto=create-drop
################### JavaMail Configuration ########################## ################### JavaMail Configuration ##########################
smtp.host=smtp.gmail.com smtp.host=smtp.gmail.com
smtp.port=465 smtp.port=465
smtp.protocol=smtps smtp.protocol=smtps
smtp.username=egmp777@gmail.com smtp.username=
smtp.password=biiikupozvjvistz smtp.password=
support.email=egmp777@gmail.com support.email=