registration project work

This commit is contained in:
eugenp 2014-08-13 12:10:29 +03:00
parent 8118f458bc
commit af81fa53ac
20 changed files with 213 additions and 208 deletions

View File

@ -3,7 +3,6 @@ package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.persistence.model.Foo;
import org.baeldung.persistence.service.IFooService;
import org.baeldung.spring.PersistenceConfig;
import org.junit.Ignore;
import org.junit.Test;
@ -36,6 +35,7 @@ public class FooServicePersistenceIntegrationTest {
}
@Test(expected = DataIntegrityViolationException.class)
@Ignore("work in progress")
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo());
}

View File

@ -1 +0,0 @@
/src

View File

@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.4.RELEASE</version>
<version>1.1.5.RELEASE</version>
</parent>
<dependencies>
@ -137,9 +137,6 @@
</build>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.springframework.security.version>3.2.4.RELEASE</org.springframework.security.version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<!-- logging -->
<org.slf4j.version>1.7.6</org.slf4j.version>
@ -152,7 +149,7 @@
<javax.inject.version>1</javax.inject.version>
<!-- Spring Data Jpa -->
<spring-data-jpa.version>1.4.1.RELEASE</spring-data-jpa.version>
<spring-data-jpa.version>1.6.2.RELEASE</spring-data-jpa.version>
<!-- guava -->
<guava.version>17.0</guava.version>

View File

@ -3,7 +3,6 @@ package org.baeldung.persistence.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.baeldung.persistence.model.User;
public interface UserRepository extends JpaRepository<User,Long>{
public interface UserRepository extends JpaRepository<User, Long> {
public User findByUsername(String username);
}

View File

@ -11,52 +11,58 @@ import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity(name="role")
@Entity(name = "role")
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
@Column(name="role")
private Integer role;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
public Role(){
super();
}
public Role(Integer role){
super();
this.role = role;
}
public Role(Integer role, User user){
super();
this.role = role;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
@Column(name = "role")
private Integer role;
public Role() {
super();
}
public Role(Integer role) {
super();
this.role = role;
}
public Role(Integer role, User user) {
super();
this.role = role;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
}

View File

@ -17,17 +17,16 @@ public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="firstName")
@Column(name = "firstName")
private String firstName;
@Column(name="lastName")
@Column(name = "lastName")
private String lastName;
@Column(name="username")
@Column(name = "username")
private String username;
@Column(name="password")
@Column(name = "password")
private String password;
@OneToOne(mappedBy = "user",fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Role role;
public Long getId() {
@ -77,8 +76,7 @@ public class User {
public void setRole(Role role) {
this.role = role;
}
@Override
public int hashCode() {
final int prime = 31;
@ -100,11 +98,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(username).append("]");
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]");
return builder.toString();
}
}

View File

@ -1,7 +1,7 @@
package org.baeldung.persistence.service;
public class EmailExistsException extends Throwable{
public class EmailExistsException extends Throwable {
public EmailExistsException(String message) {
super(message);
}

View File

@ -7,8 +7,6 @@ import org.hibernate.validator.constraints.NotEmpty;
public class RegistrationFormWithValidation {
@Email
@NotEmpty
@Size(max = 100)

View File

@ -7,43 +7,42 @@ import org.baeldung.persistence.model.Role;
import org.baeldung.persistence.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class RepositoryService implements UserService {
@Autowired
@Autowired
private UserRepository repository;
private PasswordEncoder passwordEncoder;
private final PasswordEncoder passwordEncoder;
@Autowired
private Environment env;
@Autowired
public RepositoryService(PasswordEncoder passwordEncoder, UserRepository repository) {
this.passwordEncoder = passwordEncoder;
this.repository = repository;
}
}
@Transactional
@Override
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException {
if (emailExist(userAccountData.getUsername())) {
throw new EmailExistsException("There is an account with that email adress: " + userAccountData.getUsername());
}
User user = new User();
User user = new User();
user.setFirstName(userAccountData.getFirstName());
user.setLastName(userAccountData.getLastName());
user.setPassword(userAccountData.getPassword());
user.setUsername(userAccountData.getUsername());
user.setRole(new Role(userAccountData.getRole(), user));
return repository.save(user);
return repository.save(user);
}
private boolean emailExist(String email) {
User user = repository.findByUsername(email);
if (user != null) {

View File

@ -1,4 +1,5 @@
package org.baeldung.persistence.service;
//Renamed original RegistrationForm
public class UserDto {
@ -7,51 +8,61 @@ public class UserDto {
private String lastName;
private String password;
private String username;
private Integer role;
private Integer role;
private String lastError;
public String getLastError() {
return lastError;
}
public void setLastError(String lastError) {
this.lastError = lastError;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [firstName=").append(firstName).append("]").
append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]");
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]");
return builder.toString();
}
}

View File

@ -1,7 +1,8 @@
package org.baeldung.persistence.service;
import org.baeldung.persistence.model.User;
public interface UserService {
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException;
}

View File

@ -22,33 +22,33 @@ import org.springframework.transaction.annotation.Transactional;
public class MyUserDetailsService implements UserDetailsService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsService.class);
private UserRepository userRepository;
@Autowired
public MyUserDetailsService(UserRepository repository) {
this.userRepository = repository;
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
LOGGER.debug("Loading user by username: {}", username);
User user = userRepository.findByUsername(username);
LOGGER.debug("Found user: {}", user);
if (user == null) {
//throw new UsernameNotFoundException("No user found with username: " + username);
boolean enabled = false;
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
// throw new UsernameNotFoundException("No user found with username: " + username);
boolean enabled = false;
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
@ -60,7 +60,7 @@ public class MyUserDetailsService implements UserDetailsService {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 2) {
// roles.add("ROLE_USER");
// roles.add("ROLE_USER");
roles.add("ROLE_ADMIN");
} else if (role.intValue() == 1) {
@ -69,7 +69,7 @@ public class MyUserDetailsService implements UserDetailsService {
return roles;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {

View File

@ -1,6 +1,5 @@
package org.baeldung.spring;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ -9,7 +8,6 @@ import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSenderImpl;
@Configuration
@ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
@ -24,22 +22,22 @@ public class AppConfig {
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

@ -19,11 +19,8 @@ import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
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 {
@ -46,9 +43,9 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
registry.addViewController("/admin.html");
registry.addViewController("/registration.html");
registry.addViewController("/successRegister.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
@ -82,10 +79,11 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
messageSource.setCacheSeconds(0);
return messageSource;
}
@Bean
public UserValidator userValidator() {
UserValidator userValidator = new UserValidator();
return userValidator;
}
}

View File

@ -77,5 +77,5 @@ public class PersistenceJPAConfig {
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
}

View File

@ -10,5 +10,5 @@ public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}

View File

@ -1,7 +1,5 @@
package org.baeldung.web.controller;
import java.util.Locale;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.EmailExistsException;
import org.baeldung.persistence.service.UserDto;
@ -10,17 +8,10 @@ import org.baeldung.persistence.service.UserValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
@ -30,7 +21,6 @@ import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
@Controller
@SessionAttributes("user")
public class RegistrationController {
@ -38,21 +28,18 @@ public class RegistrationController {
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationController.class);
private UserService service;
@Autowired
private MessageSource messages;
@Autowired
private JavaMailSender mailSender;
@Autowired
private UserValidator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(this.validator);
}
@Autowired
public RegistrationController(UserService service) {
this.service = service;
}
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) {
LOGGER.debug("Rendering registration page.");
@ -60,48 +47,47 @@ public class RegistrationController {
model.addAttribute("user", userDto);
return "registration";
}
/* @RequestMapping(value ="/user/registration", method = RequestMethod.POST)
public String registerUserAccount( @ModelAttribute("user") UserDto userAccountData,
BindingResult result,
WebRequest request, Errors errors) {
LOGGER.debug("Registering user account with information: {}", userAccountData);
if (result.hasErrors()) {
LOGGER.debug("Validation errors found. Rendering form view.");
return "registration";
}
LOGGER.debug("No validation errors found. Continuing registration process.");
User registered = createUserAccount(userAccountData, result);
if (registered == null) {
errors.rejectValue("lastError", "message.regError");
return "registration";
}
LOGGER.debug("Registered user account with information: {}", registered);
sendConfirmMail(userAccountData.getUsername(), request.getLocale());
return "successRegister";
//return "redirect:/";
}*/
@RequestMapping(value ="/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount( @ModelAttribute("user") UserDto userAccountData,
BindingResult result,
WebRequest request, Errors errors) {
/* @RequestMapping(value ="/user/registration", method = RequestMethod.POST)
public String registerUserAccount( @ModelAttribute("user") UserDto userAccountData,
BindingResult result,
WebRequest request, Errors errors) {
LOGGER.debug("Registering user account with information: {}", userAccountData);
if (result.hasErrors()) {
LOGGER.debug("Validation errors found. Rendering form view.");
return "registration";
}
LOGGER.debug("No validation errors found. Continuing registration process.");
User registered = createUserAccount(userAccountData, result);
if (registered == null) {
errors.rejectValue("lastError", "message.regError");
return "registration";
}
LOGGER.debug("Registered user account with information: {}", registered);
sendConfirmMail(userAccountData.getUsername(), request.getLocale());
return "successRegister";
//return "redirect:/";
}*/
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) {
LOGGER.debug("Registering user account with information: {}", userAccountData);
validator.validate(userAccountData, result);
User registered = createUserAccount(userAccountData, result);
if (registered == null) {
if (registered == null) {
result.rejectValue("lastError", "message.regError");
}
if (result.hasErrors()) {
// show errors
return new ModelAndView("registration", "user", userAccountData);
} else {
// success
return new ModelAndView("successRegister", "user", userAccountData);
}
}
}
private User createUserAccount(UserDto userAccountData, BindingResult result) {
LOGGER.debug("Creating user account with information: {}", userAccountData);
User registered = null;
@ -110,18 +96,8 @@ public class RegistrationController {
} catch (EmailExistsException e) {
// TODO Auto-generated catch block
return null;
}
}
return registered;
}
private void sendConfirmMail(String address, Locale locale){
String recipientAddress = address;
String subject = "Registration Confirmation";
String message = messages.getMessage("message.regSucc", null, locale);
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(recipientAddress);
email.setSubject(subject);
email.setText(message);
mailSender.send(email);
}
}

View File

@ -1,17 +1,10 @@
################### 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
################### JavaMail Configuration ##########################
smtp.host=smtp.gmail.com
smtp.port=465
smtp.protocol=smtps
smtp.username=edson@gmail.com
smtp.password=
support.email=edson@gmail.com
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -1,10 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>spring-security-login-and-registration</name>
<name>spring-security-mvc-ldap</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
@ -16,12 +21,12 @@
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
@ -30,24 +35,14 @@
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.hibernate.eclipse.console.hibernateBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>org.hibernate.eclipse.console.hibernateNature</nature>
</natures>
</projectDescription>