Merge pull request #37 from egmp777/master
Spring Security Login and Registration
This commit is contained in:
commit
33b6d5c645
|
@ -17,16 +17,16 @@
|
||||||
<attribute name="maven.pomderived" value="true"/>
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
</classpathentry>
|
</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">
|
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||||
<attributes>
|
<attributes>
|
||||||
<attribute name="maven.pomderived" value="true"/>
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
</classpathentry>
|
</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"/>
|
<classpathentry kind="output" path="target/classes"/>
|
||||||
</classpath>
|
</classpath>
|
||||||
|
|
|
@ -35,6 +35,11 @@
|
||||||
<arguments>
|
<arguments>
|
||||||
</arguments>
|
</arguments>
|
||||||
</buildCommand>
|
</buildCommand>
|
||||||
|
<buildCommand>
|
||||||
|
<name>org.hibernate.eclipse.console.hibernateBuilder</name>
|
||||||
|
<arguments>
|
||||||
|
</arguments>
|
||||||
|
</buildCommand>
|
||||||
</buildSpec>
|
</buildSpec>
|
||||||
<natures>
|
<natures>
|
||||||
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
|
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
|
||||||
|
@ -44,5 +49,6 @@
|
||||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||||
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
|
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
|
||||||
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
|
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
|
||||||
|
<nature>org.hibernate.eclipse.console.hibernateNature</nature>
|
||||||
</natures>
|
</natures>
|
||||||
</projectDescription>
|
</projectDescription>
|
||||||
|
|
|
@ -11,7 +11,7 @@
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>1.1.5.RELEASE</version>
|
<version>1.1.4.RELEASE</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -100,6 +100,10 @@
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.hibernate</groupId>
|
||||||
<artifactId>hibernate-entitymanager</artifactId>
|
<artifactId>hibernate-entitymanager</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate</groupId>
|
||||||
|
<artifactId>hibernate-validator</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- DB dependencies -->
|
<!-- DB dependencies -->
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -137,6 +141,9 @@
|
||||||
</build>
|
</build>
|
||||||
<properties>
|
<properties>
|
||||||
<java-version>1.7</java-version>
|
<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 -->
|
<!-- logging -->
|
||||||
<org.slf4j.version>1.7.6</org.slf4j.version>
|
<org.slf4j.version>1.7.6</org.slf4j.version>
|
||||||
|
@ -149,7 +156,7 @@
|
||||||
<javax.inject.version>1</javax.inject.version>
|
<javax.inject.version>1</javax.inject.version>
|
||||||
|
|
||||||
<!-- Spring Data Jpa -->
|
<!-- 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 -->
|
||||||
<guava.version>17.0</guava.version>
|
<guava.version>17.0</guava.version>
|
||||||
|
|
|
@ -3,6 +3,7 @@ package org.baeldung.persistence.dao;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.baeldung.persistence.model.User;
|
import org.baeldung.persistence.model.User;
|
||||||
|
|
||||||
public interface UserRepository extends JpaRepository<User, Long> {
|
|
||||||
|
public interface UserRepository extends JpaRepository<User,Long>{
|
||||||
public User findByUsername(String username);
|
public User findByUsername(String username);
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,58 +11,52 @@ import javax.persistence.JoinColumn;
|
||||||
import javax.persistence.OneToOne;
|
import javax.persistence.OneToOne;
|
||||||
import javax.persistence.Table;
|
import javax.persistence.Table;
|
||||||
|
|
||||||
@Entity(name = "role")
|
|
||||||
|
@Entity(name="role")
|
||||||
@Table(name = "role")
|
@Table(name = "role")
|
||||||
public class Role {
|
public class Role {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
|
||||||
@JoinColumn(name = "user_id")
|
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
||||||
private User user;
|
@JoinColumn(name = "user_id")
|
||||||
|
private User user;
|
||||||
|
|
||||||
|
@Column(name="role")
|
||||||
|
private Integer role;
|
||||||
|
|
||||||
@Column(name = "role")
|
public Role(){
|
||||||
private Integer role;
|
super();
|
||||||
|
|
||||||
public Role() {
|
}
|
||||||
super();
|
public Role(Integer role){
|
||||||
|
super();
|
||||||
}
|
this.role = role;
|
||||||
|
}
|
||||||
public Role(Integer role) {
|
public Role(Integer role, User user){
|
||||||
super();
|
super();
|
||||||
this.role = role;
|
this.role = role;
|
||||||
}
|
this.user = user;
|
||||||
|
}
|
||||||
public Role(Integer role, User user) {
|
public Long getId() {
|
||||||
super();
|
return id;
|
||||||
this.role = role;
|
}
|
||||||
this.user = user;
|
public void setId(Long id) {
|
||||||
}
|
this.id = id;
|
||||||
|
}
|
||||||
public Long getId() {
|
public User getUser() {
|
||||||
return id;
|
return user;
|
||||||
}
|
}
|
||||||
|
public void setUser(User user) {
|
||||||
public void setId(Long id) {
|
this.user = user;
|
||||||
this.id = id;
|
}
|
||||||
}
|
public Integer getRole() {
|
||||||
|
return role;
|
||||||
public User getUser() {
|
}
|
||||||
return user;
|
public void setRole(Integer role) {
|
||||||
}
|
this.role = role;
|
||||||
|
}
|
||||||
public void setUser(User user) {
|
|
||||||
this.user = user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getRole() {
|
|
||||||
return role;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setRole(Integer role) {
|
|
||||||
this.role = role;
|
|
||||||
}
|
|
||||||
}
|
}
|
|
@ -17,16 +17,17 @@ public class User {
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
private Long id;
|
private Long id;
|
||||||
@Column(name = "firstName")
|
@Column(name="firstName")
|
||||||
private String firstName;
|
private String firstName;
|
||||||
@Column(name = "lastName")
|
@Column(name="lastName")
|
||||||
private String lastName;
|
private String lastName;
|
||||||
@Column(name = "username")
|
@Column(name="username")
|
||||||
private String username;
|
private String username;
|
||||||
@Column(name = "password")
|
@Column(name="password")
|
||||||
private String 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;
|
private Role role;
|
||||||
|
|
||||||
public Long getId() {
|
public Long getId() {
|
||||||
|
@ -76,7 +77,8 @@ public class User {
|
||||||
public void setRole(Role role) {
|
public void setRole(Role role) {
|
||||||
this.role = role;
|
this.role = role;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
|
@ -98,11 +100,11 @@ public class User {
|
||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
final StringBuilder builder = new StringBuilder();
|
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();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,7 +1,8 @@
|
||||||
package org.baeldung.persistence.service;
|
package org.baeldung.persistence.service;
|
||||||
|
|
||||||
public class EmailExistsException extends Throwable {
|
@SuppressWarnings("serial")
|
||||||
|
public class EmailExistsException extends Throwable{
|
||||||
|
|
||||||
public EmailExistsException(String message) {
|
public EmailExistsException(String message) {
|
||||||
super(message);
|
super(message);
|
||||||
}
|
}
|
||||||
|
|
|
@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,48 +1,42 @@
|
||||||
package org.baeldung.persistence.service;
|
package org.baeldung.persistence.service;
|
||||||
|
|
||||||
import javax.transaction.Transactional;
|
import javax.transaction.Transactional;
|
||||||
|
|
||||||
import org.baeldung.persistence.dao.UserRepository;
|
import org.baeldung.persistence.dao.UserRepository;
|
||||||
import org.baeldung.persistence.model.Role;
|
import org.baeldung.persistence.model.Role;
|
||||||
import org.baeldung.persistence.model.User;
|
import org.baeldung.persistence.model.User;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.core.env.Environment;
|
import org.springframework.core.env.Environment;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class RepositoryService implements UserService {
|
public class RepositoryService implements UserService {
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository repository;
|
private UserRepository repository;
|
||||||
|
|
||||||
private final PasswordEncoder passwordEncoder;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Environment env;
|
private Environment env;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public RepositoryService(PasswordEncoder passwordEncoder, UserRepository repository) {
|
public RepositoryService( UserRepository repository) {
|
||||||
this.passwordEncoder = passwordEncoder;
|
|
||||||
this.repository = repository;
|
this.repository = repository;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@Override
|
@Override
|
||||||
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException {
|
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException {
|
||||||
if (emailExist(userAccountData.getUsername())) {
|
if (emailExist(userAccountData.getUsername())) {
|
||||||
|
|
||||||
throw new EmailExistsException("There is an account with that email adress: " + 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.setFirstName(userAccountData.getFirstName());
|
||||||
user.setLastName(userAccountData.getLastName());
|
user.setLastName(userAccountData.getLastName());
|
||||||
user.setPassword(userAccountData.getPassword());
|
user.setPassword(userAccountData.getPassword());
|
||||||
user.setUsername(userAccountData.getUsername());
|
user.setUsername(userAccountData.getUsername());
|
||||||
user.setRole(new Role(userAccountData.getRole(), user));
|
user.setRole(new Role(userAccountData.getRole(), user));
|
||||||
return repository.save(user);
|
return repository.save(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean emailExist(String email) {
|
private boolean emailExist(String email) {
|
||||||
User user = repository.findByUsername(email);
|
User user = repository.findByUsername(email);
|
||||||
if (user != null) {
|
if (user != null) {
|
||||||
|
|
|
@ -1,68 +1,47 @@
|
||||||
package org.baeldung.persistence.service;
|
package org.baeldung.persistence.service;
|
||||||
|
|
||||||
//Renamed original RegistrationForm
|
|
||||||
|
|
||||||
public class UserDto {
|
public class UserDto {
|
||||||
|
|
||||||
private String firstName;
|
private String firstName;
|
||||||
private String lastName;
|
private String lastName;
|
||||||
private String password;
|
private String password;
|
||||||
private String username;
|
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() {
|
public Integer getRole() {
|
||||||
return role;
|
return role;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setRole(Integer role) {
|
public void setRole(Integer role) {
|
||||||
this.role = role;
|
this.role = role;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUsername() {
|
public String getUsername() {
|
||||||
return username;
|
return username;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUsername(String username) {
|
public void setUsername(String username) {
|
||||||
this.username = username;
|
this.username = username;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getFirstName() {
|
public String getFirstName() {
|
||||||
return firstName;
|
return firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFirstName(String firstName) {
|
public void setFirstName(String firstName) {
|
||||||
this.firstName = firstName;
|
this.firstName = firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLastName() {
|
public String getLastName() {
|
||||||
return lastName;
|
return lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLastName(String lastName) {
|
public void setLastName(String lastName) {
|
||||||
this.lastName = lastName;
|
this.lastName = lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPassword() {
|
public String getPassword() {
|
||||||
return password;
|
return password;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setPassword(String password) {
|
public void setPassword(String password) {
|
||||||
this.password = password;
|
this.password = password;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
final StringBuilder builder = new StringBuilder();
|
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();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
package org.baeldung.persistence.service;
|
package org.baeldung.persistence.service;
|
||||||
|
|
||||||
import org.baeldung.persistence.model.User;
|
import org.baeldung.persistence.model.User;
|
||||||
|
|
||||||
public interface UserService {
|
public interface UserService {
|
||||||
|
|
||||||
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException;
|
public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,22 +1,33 @@
|
||||||
package org.baeldung.persistence.service;
|
package org.baeldung.persistence.service;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import org.springframework.validation.Errors;
|
import org.springframework.validation.Errors;
|
||||||
import org.springframework.validation.ValidationUtils;
|
import org.springframework.validation.ValidationUtils;
|
||||||
import org.springframework.validation.Validator;
|
import org.springframework.validation.Validator;
|
||||||
|
|
||||||
public class UserValidator implements 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
|
@Override
|
||||||
public boolean supports(Class<?> clazz) {
|
public boolean supports(Class<?> clazz) {
|
||||||
return UserDto.class.isAssignableFrom(clazz);
|
return UserDto.class.isAssignableFrom(clazz);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void validate(Object obj, Errors errors) {
|
public void validate(Object obj, Errors errors) {
|
||||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "message.firstName", "Firstname is required.");
|
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "message.firstName", "Firstname is required.");
|
||||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "message.lastName", "LastName is required.");
|
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "message.lastName", "LastName is required.");
|
||||||
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "message.password", "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();
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,33 +22,33 @@ import org.springframework.transaction.annotation.Transactional;
|
||||||
public class MyUserDetailsService implements UserDetailsService {
|
public class MyUserDetailsService implements UserDetailsService {
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsService.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsService.class);
|
||||||
|
|
||||||
private UserRepository userRepository;
|
private UserRepository userRepository;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public MyUserDetailsService(UserRepository repository) {
|
public MyUserDetailsService(UserRepository repository) {
|
||||||
this.userRepository = repository;
|
this.userRepository = repository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
try {
|
try {
|
||||||
LOGGER.debug("Loading user by username: {}", username);
|
LOGGER.debug("Loading user by username: {}", username);
|
||||||
User user = userRepository.findByUsername(username);
|
User user = userRepository.findByUsername(username);
|
||||||
LOGGER.debug("Found user: {}", user);
|
LOGGER.debug("Found user: {}", user);
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
// throw new UsernameNotFoundException("No user found with username: " + username);
|
//throw new UsernameNotFoundException("No user found with username: " + username);
|
||||||
boolean enabled = false;
|
boolean enabled = false;
|
||||||
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
|
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
|
||||||
}
|
}
|
||||||
boolean enabled = true;
|
boolean enabled = true;
|
||||||
boolean accountNonExpired = true;
|
boolean accountNonExpired = true;
|
||||||
boolean credentialsNonExpired = true;
|
boolean credentialsNonExpired = true;
|
||||||
boolean accountNonLocked = 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) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
|
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
|
||||||
|
@ -60,7 +60,7 @@ public class MyUserDetailsService implements UserDetailsService {
|
||||||
List<String> roles = new ArrayList<String>();
|
List<String> roles = new ArrayList<String>();
|
||||||
|
|
||||||
if (role.intValue() == 2) {
|
if (role.intValue() == 2) {
|
||||||
// roles.add("ROLE_USER");
|
// roles.add("ROLE_USER");
|
||||||
roles.add("ROLE_ADMIN");
|
roles.add("ROLE_ADMIN");
|
||||||
|
|
||||||
} else if (role.intValue() == 1) {
|
} else if (role.intValue() == 1) {
|
||||||
|
@ -69,7 +69,7 @@ public class MyUserDetailsService implements UserDetailsService {
|
||||||
|
|
||||||
return roles;
|
return roles;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
|
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
|
||||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||||
for (String role : roles) {
|
for (String role : roles) {
|
||||||
|
|
|
@ -1,43 +1,20 @@
|
||||||
package org.baeldung.spring;
|
package org.baeldung.spring;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.context.annotation.Import;
|
import org.springframework.context.annotation.Import;
|
||||||
import org.springframework.context.annotation.PropertySource;
|
import org.springframework.context.annotation.PropertySource;
|
||||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||||
import org.springframework.core.env.Environment;
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
@ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" })
|
||||||
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
|
@Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class })
|
||||||
@PropertySource("classpath:application.properties")
|
@PropertySource("classpath:application.properties")
|
||||||
public class AppConfig {
|
public class AppConfig {
|
||||||
@Autowired
|
|
||||||
private Environment env;
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
|
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
|
||||||
return new PropertySourcesPlaceholderConfigurer();
|
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;
|
|
||||||
// }
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
package org.baeldung.spring;
|
package org.baeldung.spring;
|
||||||
|
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
|
||||||
import org.baeldung.persistence.service.UserValidator;
|
import org.baeldung.persistence.service.UserValidator;
|
||||||
import org.springframework.context.MessageSource;
|
import org.springframework.context.MessageSource;
|
||||||
import org.springframework.context.annotation.Bean;
|
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.ViewResolver;
|
||||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
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.ViewControllerRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||||
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
|
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.InternalResourceViewResolver;
|
||||||
import org.springframework.web.servlet.view.JstlView;
|
import org.springframework.web.servlet.view.JstlView;
|
||||||
|
|
||||||
|
|
||||||
@Configuration
|
@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
|
@EnableWebMvc
|
||||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
|
@ -33,7 +36,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||||
@Override
|
@Override
|
||||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||||
super.addViewControllers(registry);
|
super.addViewControllers(registry);
|
||||||
|
|
||||||
registry.addViewController("/login.html");
|
registry.addViewController("/login.html");
|
||||||
registry.addViewController("/logout.html");
|
registry.addViewController("/logout.html");
|
||||||
registry.addViewController("/homepage.html");
|
registry.addViewController("/homepage.html");
|
||||||
|
@ -42,19 +44,23 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||||
registry.addViewController("/console.html");
|
registry.addViewController("/console.html");
|
||||||
registry.addViewController("/admin.html");
|
registry.addViewController("/admin.html");
|
||||||
registry.addViewController("/registration.html");
|
registry.addViewController("/registration.html");
|
||||||
registry.addViewController("/successRegister.html");
|
registry.addViewController("/successRegister.html");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver viewResolver() {
|
public ViewResolver viewResolver() {
|
||||||
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||||
bean.setViewClass(JstlView.class);
|
bean.setViewClass(JstlView.class);
|
||||||
bean.setPrefix("/WEB-INF/view/");
|
bean.setPrefix("/WEB-INF/view/");
|
||||||
bean.setSuffix(".jsp");
|
bean.setSuffix(".jsp");
|
||||||
|
|
||||||
return bean;
|
return bean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||||
|
registry.addResourceHandler("/resources/**")
|
||||||
|
.addResourceLocations("/","/resources/");
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addInterceptors(InterceptorRegistry registry) {
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
|
@ -79,11 +85,11 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||||
messageSource.setCacheSeconds(0);
|
messageSource.setCacheSeconds(0);
|
||||||
return messageSource;
|
return messageSource;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public UserValidator userValidator() {
|
public UserValidator userValidator() {
|
||||||
UserValidator userValidator = new UserValidator();
|
UserValidator userValidator = new UserValidator();
|
||||||
return userValidator;
|
return userValidator;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,9 +1,7 @@
|
||||||
package org.baeldung.spring;
|
package org.baeldung.spring;
|
||||||
|
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||||
|
|
||||||
//import com.google.common.base.Preconditions;
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableTransactionManagement
|
@EnableTransactionManagement
|
||||||
@PropertySource({ "classpath:application.properties" })
|
@PropertySource({ "classpath:application.properties" })
|
||||||
@ComponentScan({ "org.baeldung.persistence.model" })
|
@ComponentScan({ "org.baeldung.persistence.model" })
|
||||||
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
|
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
|
||||||
public class PersistenceJPAConfig {
|
public class PersistenceJPAConfig {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Environment env;
|
private Environment env;
|
||||||
|
|
||||||
|
@ -38,12 +35,9 @@ public class PersistenceJPAConfig {
|
||||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||||
em.setDataSource(dataSource());
|
em.setDataSource(dataSource());
|
||||||
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
|
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
|
||||||
|
|
||||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||||
// vendorAdapter.set
|
|
||||||
em.setJpaVendorAdapter(vendorAdapter);
|
em.setJpaVendorAdapter(vendorAdapter);
|
||||||
em.setJpaProperties(additionalProperties());
|
em.setJpaProperties(additionalProperties());
|
||||||
|
|
||||||
return em;
|
return em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -54,7 +48,6 @@ public class PersistenceJPAConfig {
|
||||||
dataSource.setUrl(env.getProperty("jdbc.url"));
|
dataSource.setUrl(env.getProperty("jdbc.url"));
|
||||||
dataSource.setUsername(env.getProperty("jdbc.user"));
|
dataSource.setUsername(env.getProperty("jdbc.user"));
|
||||||
dataSource.setPassword(env.getProperty("jdbc.pass"));
|
dataSource.setPassword(env.getProperty("jdbc.pass"));
|
||||||
|
|
||||||
return dataSource;
|
return dataSource;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -74,8 +67,7 @@ public class PersistenceJPAConfig {
|
||||||
final Properties hibernateProperties = new Properties();
|
final Properties hibernateProperties = new Properties();
|
||||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||||
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
|
|
||||||
return hibernateProperties;
|
return hibernateProperties;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,5 +10,5 @@ public class SecSecurityConfig {
|
||||||
public SecSecurityConfig() {
|
public SecSecurityConfig() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
package org.baeldung.web.controller;
|
package org.baeldung.web.controller;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
import org.baeldung.persistence.model.User;
|
import org.baeldung.persistence.model.User;
|
||||||
import org.baeldung.persistence.service.EmailExistsException;
|
import org.baeldung.persistence.service.EmailExistsException;
|
||||||
import org.baeldung.persistence.service.UserDto;
|
import org.baeldung.persistence.service.UserDto;
|
||||||
|
@ -8,6 +9,8 @@ import org.baeldung.persistence.service.UserValidator;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.MessageSource;
|
||||||
|
import org.springframework.mail.javamail.JavaMailSender;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.ui.Model;
|
import org.springframework.ui.Model;
|
||||||
import org.springframework.validation.BindingResult;
|
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.ModelAttribute;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMethod;
|
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.context.request.WebRequest;
|
||||||
import org.springframework.web.servlet.ModelAndView;
|
import org.springframework.web.servlet.ModelAndView;
|
||||||
|
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
@SessionAttributes("user")
|
|
||||||
public class RegistrationController {
|
public class RegistrationController {
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationController.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationController.class);
|
||||||
private UserService service;
|
private UserService service;
|
||||||
@Autowired
|
@Autowired
|
||||||
|
private MessageSource messages;
|
||||||
|
@Autowired
|
||||||
|
private JavaMailSender mailSender;
|
||||||
|
@Autowired
|
||||||
private UserValidator validator;
|
private UserValidator validator;
|
||||||
|
|
||||||
@InitBinder
|
@InitBinder
|
||||||
protected void initBinder(WebDataBinder binder) {
|
protected void initBinder(WebDataBinder binder) {
|
||||||
binder.setValidator(this.validator);
|
binder.setValidator(this.validator);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public RegistrationController(UserService service) {
|
public RegistrationController(UserService service) {
|
||||||
this.service = service;
|
this.service = service;
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
|
@RequestMapping(value = "/user/registration", method = RequestMethod.GET)
|
||||||
public String showRegistrationForm(WebRequest request, Model model) {
|
public String showRegistrationForm(WebRequest request, Model model) {
|
||||||
LOGGER.debug("Rendering registration page.");
|
LOGGER.debug("Rendering registration page.");
|
||||||
|
@ -47,57 +52,34 @@ public class RegistrationController {
|
||||||
model.addAttribute("user", userDto);
|
model.addAttribute("user", userDto);
|
||||||
return "registration";
|
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)
|
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
|
||||||
public ModelAndView registerUserAccount(@ModelAttribute("user") UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) {
|
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) {
|
||||||
LOGGER.debug("Registering user account with information: {}", userAccountData);
|
boolean goodEmailCheck = validator.validateEmail(userAccountData.getUsername());
|
||||||
validator.validate(userAccountData, result);
|
if (!goodEmailCheck)
|
||||||
User registered = createUserAccount(userAccountData, result);
|
result.rejectValue("username", "message.badEmail");
|
||||||
if (registered == null) {
|
User registered = null;
|
||||||
result.rejectValue("lastError", "message.regError");
|
if (!result.hasErrors())
|
||||||
|
registered = createUserAccount(userAccountData, result);
|
||||||
|
if (registered == null && !userAccountData.getUsername().isEmpty() && goodEmailCheck) {
|
||||||
|
result.rejectValue("username", "message.regError");
|
||||||
}
|
}
|
||||||
if (result.hasErrors()) {
|
if (result.hasErrors()) {
|
||||||
// show errors
|
|
||||||
return new ModelAndView("registration", "user", userAccountData);
|
return new ModelAndView("registration", "user", userAccountData);
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
// success
|
|
||||||
return new ModelAndView("successRegister", "user", userAccountData);
|
return new ModelAndView("successRegister", "user", userAccountData);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private User createUserAccount(UserDto userAccountData, BindingResult result) {
|
private User createUserAccount(UserDto userAccountData, BindingResult result) {
|
||||||
LOGGER.debug("Creating user account with information: {}", userAccountData);
|
|
||||||
User registered = null;
|
User registered = null;
|
||||||
try {
|
try {
|
||||||
registered = service.registerNewUserAccount(userAccountData);
|
registered = service.registerNewUserAccount(userAccountData);
|
||||||
} catch (EmailExistsException e) {
|
} catch (EmailExistsException e) {
|
||||||
// TODO Auto-generated catch block
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return registered;
|
return registered;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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.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.regError=An account for that username/email already exists. Please enter a different username.
|
||||||
message.lastName=Last name is required
|
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.email=Email
|
||||||
label.user.firstName=First name
|
label.user.firstName=First name
|
||||||
label.user.lastName=Last name
|
label.user.lastName=Last name
|
||||||
|
|
|
@ -3,14 +3,15 @@ message.password=Por favor ingrese una clave
|
||||||
message.unauth=Acceso denegado !!
|
message.unauth=Acceso denegado !!
|
||||||
message.badCredentials=Usuario o clave invalida
|
message.badCredentials=Usuario o clave invalida
|
||||||
message.sessionExpired=La sesion expiro
|
message.sessionExpired=La sesion expiro
|
||||||
message.logoutError=Lo sentimos, hubo problemas en logout
|
message.logoutError=Lo sentimos, hubo problemas al salir
|
||||||
message.logoutSucc=Logout con exito
|
message.logoutSucc=Salida con exito
|
||||||
message.regSucc=Se registro correctamente. Le enviaremos un mensaje de confirmacion a su direccion de email.
|
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.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.lastName=Por favor ingrese su apellido
|
||||||
message.firstName=El campo First Name es obligatorio
|
message.firstName=Por favor ingrese su nombre
|
||||||
|
message.badEmail=Direccion de correo no es valida
|
||||||
label.user.email=Email
|
label.user.email=Email
|
||||||
label.user.firstName=Nombre
|
label.user.firstName=Nombre
|
||||||
label.user.lastName=Apellido
|
label.user.lastName=Apellido
|
||||||
label.user.password=Clave
|
label.user.password=Clave
|
||||||
label.login=Loguee aqui
|
label.login=Autehtifiquese aqui
|
|
@ -29,22 +29,13 @@
|
||||||
</http>
|
</http>
|
||||||
<beans:bean id="myAuthenticationSuccessHandler"
|
<beans:bean id="myAuthenticationSuccessHandler"
|
||||||
class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler" />
|
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-manager>
|
||||||
<authentication-provider user-service-ref="userDetailsService">
|
<authentication-provider user-service-ref="userDetailsService">
|
||||||
<!-- <password-encoder ref="passwordEncoder"/> -->
|
|
||||||
</authentication-provider>
|
</authentication-provider>
|
||||||
</authentication-manager>
|
</authentication-manager>
|
||||||
|
|
||||||
<!-- This is used to hash the password of the user.(For article 2) -->
|
|
||||||
<beans:bean id="passwordEncoder"
|
<beans:bean id="passwordEncoder"
|
||||||
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"
|
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"
|
||||||
autowire="constructor" />
|
autowire="constructor" />
|
||||||
<!-- <beans:constructor-arg index="0" value="10"/> </beans:bean> -->
|
|
||||||
|
|
||||||
<beans:bean id="userDetailsService" class="org.baeldung.security.MyUserDetailsService"
|
<beans:bean id="userDetailsService" class="org.baeldung.security.MyUserDetailsService"
|
||||||
autowire="constructor" />
|
autowire="constructor" />
|
||||||
</beans:beans>
|
</beans:beans>
|
|
@ -5,7 +5,9 @@
|
||||||
<sec:authorize ifAnyGranted ="ROLE_USER">
|
<sec:authorize ifAnyGranted ="ROLE_USER">
|
||||||
<spring:message code="message.unauth" ></spring:message>
|
<spring:message code="message.unauth" ></spring:message>
|
||||||
</sec:authorize>
|
</sec:authorize>
|
||||||
<head></head>
|
<head>
|
||||||
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||||
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
|
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
|
||||||
<html>
|
<html>
|
||||||
<head></head>
|
<head>
|
||||||
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<h1>This is the landing page for the admin</h1>
|
<h1>This is the landing page for the admin</h1>
|
||||||
|
|
|
@ -2,6 +2,7 @@
|
||||||
<%@ page session="true" %>
|
<%@ page session="true" %>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
<title>Home</title>
|
<title>Home</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
|
@ -2,7 +2,9 @@
|
||||||
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
|
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
|
||||||
<%@ page session="true" %>
|
<%@ page session="true" %>
|
||||||
<html>
|
<html>
|
||||||
<head></head>
|
<head>
|
||||||
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<body>
|
<body>
|
||||||
|
|
|
@ -1,10 +1,12 @@
|
||||||
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
<title>Home</title>
|
<title>Home</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>
|
<h1 class="alert alert-error">
|
||||||
<spring:message code="message.sessionExpired" ></spring:message>
|
<spring:message code="message.sessionExpired" ></spring:message>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
|
|
|
@ -5,28 +5,17 @@
|
||||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
|
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
|
||||||
<fmt:setBundle basename="messages" />
|
<fmt:setBundle basename="messages" />
|
||||||
<%@ page session="true"%>
|
<%@ 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.password" var="noPass" />
|
||||||
<fmt:message key="message.username" var="noUser" />
|
<fmt:message key="message.username" var="noUser" />
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<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">
|
<script type="text/javascript">
|
||||||
function validate() {
|
function validate() {
|
||||||
if (document.f.j_username.value == ""
|
if (document.f.j_username.value == ""
|
||||||
|
@ -73,6 +62,7 @@
|
||||||
|
|
||||||
</form>
|
</form>
|
||||||
<br> Current Locale : ${pageContext.response.locale}
|
<br> Current Locale : ${pageContext.response.locale}
|
||||||
|
<br>
|
||||||
<a href="<c:url value="/user/registration" />">Sign Up</a>
|
<a href="<c:url value="/user/registration" />">Sign Up</a>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
|
|
@ -2,6 +2,10 @@
|
||||||
<%@ taglib prefix="sec"
|
<%@ taglib prefix="sec"
|
||||||
uri="http://www.springframework.org/security/tags"%>
|
uri="http://www.springframework.org/security/tags"%>
|
||||||
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
|
<%@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}">
|
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
|
||||||
<div id="error">
|
<div id="error">
|
||||||
<spring:message code="message.logoutError"></spring:message>
|
<spring:message code="message.logoutError"></spring:message>
|
||||||
|
@ -12,8 +16,6 @@
|
||||||
<spring:message code="message.logoutSucc"></spring:message>
|
<spring:message code="message.logoutSucc"></spring:message>
|
||||||
</div>
|
</div>
|
||||||
</c:if>
|
</c:if>
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||||
<title>Logged Out</title>
|
<title>Logged Out</title>
|
||||||
</head>
|
</head>
|
||||||
|
|
|
@ -5,52 +5,40 @@
|
||||||
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
|
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
|
||||||
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
|
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
|
||||||
<%@ page session="false"%>
|
<%@ 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>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||||
<title>Registration</title>
|
<title>Registration</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<H1>This is the registration page</H1>
|
<H1>This is the registration page</H1>
|
||||||
<form:form modelAttribute="user" method="POST" enctype="utf8" role="form" >
|
<form:form modelAttribute="user" method="POST" enctype="utf8" role="form" >
|
||||||
<form:errors path="lastError" cssClass="fieldError"/>
|
|
||||||
<br>
|
<br>
|
||||||
<tr>
|
<tr>
|
||||||
<td><label>First Name:</label></td>
|
<td><label>First Name:</label></td>
|
||||||
<td><form:input path="firstName" value =""/></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>
|
||||||
<tr>
|
<tr>
|
||||||
<td><label>Last Name:</label></td>
|
<td><label>Last Name:</label></td>
|
||||||
<td><form:input path="lastName" value =""/></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>
|
||||||
<tr>
|
<tr>
|
||||||
<td><label>Username (your e-mail address):</label></td>
|
<td><label>Username (your e-mail address):</label></td>
|
||||||
<td><form:input path="username" value=""/></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>
|
||||||
<tr>
|
<tr>
|
||||||
<td><label>Password:</label></td>
|
<td><label>Password:</label></td>
|
||||||
<td><form:input path="password" value=""/></td>
|
<td><form:input path="password" value="" type="password"/></td>
|
||||||
<form:errors path="password" class="errors" />
|
<form:errors path="password" cssClass="alert alert-error" element="div" />
|
||||||
</tr>
|
</tr>
|
||||||
<input type="hidden" name="role" value="1" />
|
<input type="hidden" name="role" value="1" />
|
||||||
<button type="submit">submit</button>
|
<button type="submit">submit</button>
|
||||||
</form:form>
|
</form:form>
|
||||||
|
<br>
|
||||||
|
<a href="<c:url value="login.html" />">Back to Login</a>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
|
@ -8,12 +8,13 @@
|
||||||
|
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
|
<link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet">
|
||||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||||
<title>Registration Success</title>
|
<title>Registration Success</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<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>
|
<a href="<c:url value="login.html" />"><spring:message code="label.login"></spring:message></a>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
6167
spring-security-login-error-handling/src/main/webapp/resources/bootstrap.css
vendored
Normal file
6167
spring-security-login-error-handling/src/main/webapp/resources/bootstrap.css
vendored
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue