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"/>
</attributes>
</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"/>
</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.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
//NOV 5th
// public User findByVerificationToken(VerificationToken token);
//OCT 21
public void delete(User user);
public User findByEmail(String email);
public void delete(User user);
}

View File

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

View File

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

View File

@ -1,15 +1,17 @@
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;
//OCT 21 EMAIL VERIFICATION
public User getRegisteredUser(String email);
public User getUser(String verificationToken);
public void verifyRegisteredUser(User user);
public void addVerificationToken(User user, String token);
}

View File

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

View File

@ -3,6 +3,7 @@ package org.baeldung.persistence.service;
import javax.transaction.Transactional;
import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.dao.VerificationTokenRepository;
import org.baeldung.persistence.model.Role;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken;
@ -12,49 +13,63 @@ import org.springframework.stereotype.Service;
@Service
public class UserService implements IUserService {
@Autowired
private UserRepository repository;
@Autowired
private UserRepository repository;
// NOV 6
@Autowired
private VerificationTokenRepository tokenRepository;
@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());
// ROLE WILL ALWAYS BE USER. HARDCODING IT
user.setRole(new Role(Integer.valueOf(1), user));
//OCT 21 EMAIL VERIFICATION VERSION
//MIGHT CHANGE HERE
VerificationToken myToken = new VerificationToken(accountDto.getToken(),user);
user.setVerificationToken(myToken);
return repository.save(user);
}
@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);
}
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
//OCT 21 EMAIL VERIFICATION
@Override
public User getRegisteredUser(String email){
User user = repository.findByEmail(email);
return user;
}
@Transactional
@Override
public void verifyRegisteredUser(User user){
repository.save(user);
}
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
@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);
}
@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;
@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 })
@PropertySource("classpath:application.properties")
public class AppConfig {
@Autowired
private Environment env;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
//OCT 21
@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 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;
}
}

View File

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