cleanup work
This commit is contained in:
parent
33b6d5c645
commit
1222077785
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -1,8 +1,8 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class EmailExistsException extends Throwable{
|
||||
|
||||
public class EmailExistsException extends Throwable {
|
||||
|
||||
public EmailExistsException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
|
|
@ -10,33 +10,33 @@ import org.springframework.stereotype.Service;
|
|||
|
||||
@Service
|
||||
public class RepositoryService implements UserService {
|
||||
@Autowired
|
||||
@Autowired
|
||||
private UserRepository repository;
|
||||
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
|
||||
@Autowired
|
||||
public RepositoryService( UserRepository repository) {
|
||||
public RepositoryService(UserRepository repository) {
|
||||
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) {
|
||||
|
|
|
@ -5,43 +5,52 @@ public class UserDto {
|
|||
private String lastName;
|
||||
private String password;
|
||||
private String username;
|
||||
private Integer role;
|
||||
|
||||
private Integer role;
|
||||
|
||||
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("]").append("[password").append(password).append("]");
|
||||
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]").append("[password").append(password).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
package org.baeldung.persistence.service;
|
||||
|
||||
import org.baeldung.persistence.model.User;
|
||||
|
||||
public interface UserService {
|
||||
|
||||
|
||||
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException;
|
||||
|
||||
}
|
||||
|
|
|
@ -10,18 +10,18 @@ public class UserValidator implements Validator {
|
|||
private Pattern pattern;
|
||||
private Matcher matcher;
|
||||
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
|
||||
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return UserDto.class.isAssignableFrom(clazz);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void validate(Object obj, Errors errors) {
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "message.firstName", "Firstname is required.");
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "message.lastName", "LastName is required.");
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "message.password", "LastName is required.");
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required.");
|
||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required.");
|
||||
}
|
||||
|
||||
public boolean validateEmail(String email) {
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -12,7 +12,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
|||
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
|
||||
@PropertySource("classpath:application.properties")
|
||||
public class AppConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
|
||||
return new PropertySourcesPlaceholderConfigurer();
|
||||
|
|
|
@ -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 {
|
||||
|
||||
|
@ -44,9 +41,9 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
|||
registry.addViewController("/console.html");
|
||||
registry.addViewController("/admin.html");
|
||||
registry.addViewController("/registration.html");
|
||||
registry.addViewController("/successRegister.html");
|
||||
registry.addViewController("/successRegister.html");
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||
|
@ -55,11 +52,10 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
|||
bean.setSuffix(".jsp");
|
||||
return bean;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**")
|
||||
.addResourceLocations("/","/resources/");
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -85,11 +81,11 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
|||
messageSource.setCacheSeconds(0);
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public UserValidator userValidator() {
|
||||
UserValidator userValidator = new UserValidator();
|
||||
return userValidator;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -22,7 +22,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
|
|||
@ComponentScan({ "org.baeldung.persistence.model" })
|
||||
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
|
||||
public class PersistenceJPAConfig {
|
||||
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
|
@ -69,5 +69,5 @@ public class PersistenceJPAConfig {
|
|||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -10,5 +10,5 @@ public class SecSecurityConfig {
|
|||
public SecSecurityConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -9,8 +9,6 @@ import org.baeldung.persistence.service.UserValidator;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
|
@ -23,28 +21,25 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
|||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
|
||||
@Controller
|
||||
public class RegistrationController {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationController.class);
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
|
||||
|
||||
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.");
|
||||
|
@ -52,7 +47,7 @@ public class RegistrationController {
|
|||
model.addAttribute("user", userDto);
|
||||
return "registration";
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
||||
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) {
|
||||
boolean goodEmailCheck = validator.validateEmail(userAccountData.getUsername());
|
||||
|
@ -71,15 +66,15 @@ public class RegistrationController {
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private User createUserAccount(UserDto userAccountData, BindingResult result) {
|
||||
User registered = null;
|
||||
try {
|
||||
registered = service.registerNewUserAccount(userAccountData);
|
||||
} catch (EmailExistsException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return registered;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue