Merge pull request #37 from egmp777/master

Spring Security Login and Registration
This commit is contained in:
Eugen 2014-08-15 14:54:51 +03:00
commit 33b6d5c645
31 changed files with 6371 additions and 342 deletions

View File

@ -17,16 +17,16 @@
<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="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -35,6 +35,11 @@
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.hibernate.eclipse.console.hibernateBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
@ -44,5 +49,6 @@
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>org.hibernate.eclipse.console.hibernateNature</nature>
</natures>
</projectDescription>

View File

@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.5.RELEASE</version>
<version>1.1.4.RELEASE</version>
</parent>
<dependencies>
@ -100,6 +100,10 @@
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- DB dependencies -->
<dependency>
@ -137,6 +141,9 @@
</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>
@ -149,7 +156,7 @@
<javax.inject.version>1</javax.inject.version>
<!-- Spring Data Jpa -->
<spring-data-jpa.version>1.6.2.RELEASE</spring-data-jpa.version>
<spring-data-jpa.version>1.4.1.RELEASE</spring-data-jpa.version>
<!-- guava -->
<guava.version>17.0</guava.version>

View File

@ -3,6 +3,7 @@ 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,58 +11,52 @@ 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;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
@Column(name="role")
private Integer 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;
}
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,16 +17,17 @@ 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() {
@ -76,7 +77,8 @@ public class User {
public void setRole(Role role) {
this.role = role;
}
@Override
public int hashCode() {
final int prime = 31;
@ -98,11 +100,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,8 @@
package org.baeldung.persistence.service;
public class EmailExistsException extends Throwable {
@SuppressWarnings("serial")
public class EmailExistsException extends Throwable{
public EmailExistsException(String message) {
super(message);
}

View File

@ -1,73 +0,0 @@
package org.baeldung.persistence.service;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
public class RegistrationFormWithValidation {
@Email
@NotEmpty
@Size(max = 100)
private String email;
@NotEmpty
@Size(max = 100)
private String firstName;
@NotEmpty
@Size(max = 100)
private String lastName;
private String password;
private String passwordVerification;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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;
}
public String getPasswordVerification() {
return passwordVerification;
}
public void setPasswordVerification(String passwordVerification) {
this.passwordVerification = passwordVerification;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]");
return builder.toString();
}
}

View File

@ -1,48 +1,42 @@
package org.baeldung.persistence.service;
import javax.transaction.Transactional;
import org.baeldung.persistence.dao.UserRepository;
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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class RepositoryService implements UserService {
@Autowired
@Autowired
private UserRepository repository;
private final PasswordEncoder passwordEncoder;
@Autowired
private Environment env;
@Autowired
public RepositoryService(PasswordEncoder passwordEncoder, UserRepository repository) {
this.passwordEncoder = passwordEncoder;
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) {

View File

@ -1,68 +1,47 @@
package org.baeldung.persistence.service;
//Renamed original RegistrationForm
public class UserDto {
private String firstName;
private String lastName;
private String password;
private String username;
private Integer role;
private String lastError;
public String getLastError() {
return lastError;
}
public void setLastError(String lastError) {
this.lastError = lastError;
}
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("]");
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();
}
}

View File

@ -1,8 +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

@ -1,22 +1,33 @@
package org.baeldung.persistence.service;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
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) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
}

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,43 +1,20 @@
package org.baeldung.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
@Configuration
@ComponentScan(basePackages = { "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();
}
// @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,7 +1,6 @@
package org.baeldung.spring;
import java.util.Locale;
import org.baeldung.persistence.service.UserValidator;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
@ -12,6 +11,7 @@ import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
@ -19,8 +19,11 @@ 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 {
@ -33,7 +36,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/login.html");
registry.addViewController("/logout.html");
registry.addViewController("/homepage.html");
@ -42,19 +44,23 @@ 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();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/","/resources/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
@ -79,11 +85,11 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
messageSource.setCacheSeconds(0);
return messageSource;
}
@Bean
public UserValidator userValidator() {
UserValidator userValidator = new UserValidator();
return userValidator;
}
}

View File

@ -1,9 +1,7 @@
package org.baeldung.spring;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ -18,14 +16,13 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:application.properties" })
@ComponentScan({ "org.baeldung.persistence.model" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJPAConfig {
@Autowired
private Environment env;
@ -38,12 +35,9 @@ public class PersistenceJPAConfig {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// vendorAdapter.set
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@ -54,7 +48,6 @@ public class PersistenceJPAConfig {
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@ -74,8 +67,7 @@ public class PersistenceJPAConfig {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
}

View File

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

View File

@ -1,5 +1,6 @@
package org.baeldung.web.controller;
import javax.validation.Valid;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.EmailExistsException;
import org.baeldung.persistence.service.UserDto;
@ -8,6 +9,8 @@ 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;
@ -17,29 +20,31 @@ import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
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 {
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.");
@ -47,57 +52,34 @@ 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) {
LOGGER.debug("Registering user account with information: {}", userAccountData);
validator.validate(userAccountData, result);
User registered = createUserAccount(userAccountData, result);
if (registered == null) {
result.rejectValue("lastError", "message.regError");
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) {
boolean goodEmailCheck = validator.validateEmail(userAccountData.getUsername());
if (!goodEmailCheck)
result.rejectValue("username", "message.badEmail");
User registered = null;
if (!result.hasErrors())
registered = createUserAccount(userAccountData, result);
if (registered == null && !userAccountData.getUsername().isEmpty() && goodEmailCheck) {
result.rejectValue("username", "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;
try {
registered = service.registerNewUserAccount(userAccountData);
} catch (EmailExistsException e) {
// TODO Auto-generated catch block
return null;
}
}
return registered;
}
}
}

View File

@ -8,7 +8,8 @@ message.logoutSucc=You logged out successfully
message.regSucc=You registered successfully. We will send you a confirmation message to your email account.
message.regError=An account for that username/email already exists. Please enter a different username.
message.lastName=Last name is required
message.firstName=First name is required
message.firstName=First name required
message.badEmail=Invalid email address
label.user.email=Email
label.user.firstName=First name
label.user.lastName=Last name

View File

@ -3,14 +3,15 @@ message.password=Por favor ingrese una clave
message.unauth=Acceso denegado !!
message.badCredentials=Usuario o clave invalida
message.sessionExpired=La sesion expiro
message.logoutError=Lo sentimos, hubo problemas en logout
message.logoutSucc=Logout con exito
message.logoutError=Lo sentimos, hubo problemas al salir
message.logoutSucc=Salida con exito
message.regSucc=Se registro correctamente. Le enviaremos un mensaje de confirmacion a su direccion de email.
message.regError=Ya existe una cuenta con ese nombre de usuario. Ingrese un nombre de usuario diferente.
message.lastName=El campo Last Name es obligatorio
message.firstName=El campo First Name es obligatorio
message.lastName=Por favor ingrese su apellido
message.firstName=Por favor ingrese su nombre
message.badEmail=Direccion de correo no es valida
label.user.email=Email
label.user.firstName=Nombre
label.user.lastName=Apellido
label.user.password=Clave
label.login=Loguee aqui
label.login=Autehtifiquese aqui

View File

@ -29,22 +29,13 @@
</http>
<beans:bean id="myAuthenticationSuccessHandler"
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
<!-- <authentication-manager> <authentication-provider> <user-service> <user
name="user1" password="user1Pass" authorities="ROLE_USER" /> <user name="admin1"
password="admin1Pass" authorities="ROLE_ADMIN" /> </user-service> </authentication-provider> -->
<!-- Authentication from database.(For article 2) -->
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<!-- <password-encoder ref="passwordEncoder"/> -->
</authentication-provider>
</authentication-manager>
<!-- This is used to hash the password of the user.(For article 2) -->
<beans:bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"
autowire="constructor" />
<!-- <beans:constructor-arg index="0" value="10"/> </beans:bean> -->
<beans:bean id="userDetailsService" class="org.baeldung.security.MyUserDetailsService"
autowire="constructor" />
</beans:beans>

View File

@ -5,7 +5,9 @@
<sec:authorize ifAnyGranted ="ROLE_USER">
<spring:message code="message.unauth" ></spring:message>
</sec:authorize>
<head></head>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
</head>
<body>

View File

@ -1,7 +1,9 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head></head>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
</head>
<body>
<h1>This is the landing page for the admin</h1>

View File

@ -2,6 +2,7 @@
<%@ page session="true" %>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title>Home</title>
</head>
<body>

View File

@ -2,7 +2,9 @@
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page session="true" %>
<html>
<head></head>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
</head>
<body>
<body>

View File

@ -1,10 +1,12 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<title>Home</title>
</head>
<body>
<h1>
<h1 class="alert alert-error">
<spring:message code="message.sessionExpired" ></spring:message>
</h1>

View File

@ -5,28 +5,17 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:setBundle basename="messages" />
<%@ page session="true"%>
<c:if test="${param.error != null}">
<div id="error">
<spring:message code="message.badCredentials"></spring:message>
</div>
</c:if>
<c:if test="${param.regSucc == 1}">
<div id="error">
<spring:message code="message.regSucc"></spring:message>
</div>
</c:if>
<c:if test="${param.regError == 1}">
<div id="error">
<spring:message code="message.regError"></spring:message>
</div>
<a href="registration.html">Register</a>
</c:if>
<fmt:message key="message.password" var="noPass" />
<fmt:message key="message.username" var="noUser" />
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<c:if test="${param.error != null}">
<div class="alert alert-error">
<spring:message code="message.badCredentials"></spring:message>
</div>
</c:if>
<script type="text/javascript">
function validate() {
if (document.f.j_username.value == ""
@ -73,6 +62,7 @@
</form>
<br> Current Locale : ${pageContext.response.locale}
<br>
<a href="<c:url value="/user/registration" />">Sign Up</a>
</body>

View File

@ -2,6 +2,10 @@
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<div id="error">
<spring:message code="message.logoutError"></spring:message>
@ -12,8 +16,6 @@
<spring:message code="message.logoutSucc"></spring:message>
</div>
</c:if>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Logged Out</title>
</head>

View File

@ -5,52 +5,40 @@
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<%@ page session="false"%>
<c:if test="${param.regSucc == 1}">
<div id="error">
<spring:message code="message.regSucc"></spring:message>
</div>
</c:if>
<c:if test="${param.regError == 1}">
<div id="error">
<spring:message code="message.regError"></spring:message>
<a href="<c:url value="/login" />"><spring:message code="label.login"></spring:message></a>
</div>
</c:if>
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Registration</title>
</head>
<body>
<H1>This is the registration page</H1>
<form:form modelAttribute="user" method="POST" enctype="utf8" role="form" >
<form:errors path="lastError" cssClass="fieldError"/>
<br>
<tr>
<td><label>First Name:</label></td>
<td><form:input path="firstName" value =""/></td>
<form:errors path="firstName" class="errors" />
<form:errors path="firstName" cssClass="alert alert-error" element="div" />
</tr>
<tr>
<td><label>Last Name:</label></td>
<td><form:input path="lastName" value =""/></td>
<form:errors path="lastName" class="errors" />
<form:errors path="lastName" cssClass="alert alert-error" element="div" />
</tr>
<tr>
<td><label>Username (your e-mail address):</label></td>
<td><form:input path="username" value=""/></td>
<form:errors path="username" class="errors" />
<form:errors path="username" cssClass="alert alert-error" element="div" />
</tr>
<tr>
<td><label>Password:</label></td>
<td><form:input path="password" value=""/></td>
<form:errors path="password" class="errors" />
<td><form:input path="password" value="" type="password"/></td>
<form:errors path="password" cssClass="alert alert-error" element="div" />
</tr>
<input type="hidden" name="role" value="1" />
<button type="submit">submit</button>
</form:form>
<br>
<a href="<c:url value="login.html" />">Back to Login</a>
</body>
</html>

View File

@ -8,12 +8,13 @@
<html>
<head>
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Registration Success</title>
</head>
<body>
<spring:message code="message.regSucc"></spring:message>
<h1> <spring:message code="message.regSucc"></spring:message> </h1>
<a href="<c:url value="login.html" />"><spring:message code="label.login"></spring:message></a>
</body>
</html>

File diff suppressed because it is too large Load Diff